'HOC functional component with extra props in TypeScript

I'm trying to achieve a "click twice to confirm" kind of button with a HOC. I want to be provided a text to display in a tooltip (from MUI) upon first click, and execute the onClick action only on second click.

I have managed to do that when the confirmation text is provided upon creating the HOC'd component: const DoubleClickButton = withClickConfirmation(Button, "Click again to confirm"); but I would like the HOC to be a bit more generic and add the confirmation text in the props of the HOC'd component like so:

<DoubleClickButton onClick={() => alert("hello!")} confirmationText="Click again to confirm">
    Click me please
</DoubleClickButton>

Here is my HOC:

import React, { useState } from "react";
import Tooltip from "@mui/material/Tooltip";

export function withClickConfirmation<T extends { onClick: Function }>(
  Component: React.ComponentType<T>
) {
  const Wrapped = (props: WithClickConfirmationWrappedProps<T>) => {
    const { confirmationText, ...wrappedProps } = props;
    const [confirmationState, setConfirmationState] =
      useState<ConfirmationState>("awaitingClick");

    if (confirmationState === "awaitingClick") {
      return (
        <Component
          {...wrappedProps}
          onClick={() => setConfirmationState("pendingConfirmation")}
        />
      );
    } else {
      return (
        <Tooltip title={confirmationText} open>
          <div onClick={() => setConfirmationState("awaitingClick")}>
            <Component {...wrappedProps} />
          </div>
        </Tooltip>
      );
    }
  };

  Wrapped.displayName = `withClickConfirmation(${Component.displayName})`;
  return Wrapped;
}

export type WithClickConfirmationWrappedProps<T> = T & {
  confirmationText: string;
};

type ConfirmationState = "awaitingClick" | "pendingConfirmation";

The problem is that Typescript is complaining about the <Component... /> type and I don't understand why. I think I understand the error itself, but not why it is thrown. Here's the error:

TS2322: Type 'Omit<WithClickConfirmationWrappedProps<T>, "confirmationText"> & { onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
   Type 'Omit<WithClickConfirmationWrappedProps<T>, "confirmationText"> & { onClick: () => void; }' is not assignable to type 'T'.
     'Omit<WithClickConfirmationWrappedProps<T>, "confirmationText"> & { onClick: () => void; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ onClick: Function; }'.

Thank you :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source