Thomas Timmermans
Thomas Timmermans

Reputation: 402

React typescript Types of property 'type' are incompatible

I've a custom button like this:

export enum ButtonTypes {
  'button',
  'submit',
  'reset',
  undefined,
}

type CustomButtonProps = {
    type: ButtonTypes;
};

const CustomButton: React.FC<CustomButtonProps> = ({
    children,
    ...otherProps
}) => {
    return (
        <button className="custom-button" {...otherProps}>
            {children}
        </button>
    );
};

export default CustomButton;

In parent component:

<CustomButton type={ButtonTypes.submit}>
  Sign in
</CustomButton>

Error I get:

Type '{ children: ReactNode; type: ButtonTypes; className: string; }' is not assignable to 

type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'.
  Type '{ children: ReactNode; type: ButtonTypes; className: string; }' is not assignable to type 'ButtonHTMLAttributes<HTMLButtonElement>'.
    Types of property 'type' are incompatible.
      Type 'ButtonTypes' is not assignable to type '"button" | "submit" | "reset" | undefined'.

I'm quite new to typescript so may be a stupid question. However, I can't find a solution for it.

Everything compiles fine when I don't spread the props like:

const CustomButton: React.FC<CustomButtonProps> = ({
    children
}, type) => {
    return (
        <button className="custom-button" type={type}>
            {children}
        </button>
    );
};

export default CustomButton;

Upvotes: 1

Views: 6445

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282040

When you use enums like you are doing, ButtonTypes.submit will return you a integer instead of the string submit and that is the type that button expects as a prop

You can define string enums and it will work fine for you. Also you need to define children prop type

export enum ButtonTypes {
  Button = "button",
  Submit = "submit",
  React = "reset"
}

type CustomButtonProps = {
  children: ReactNode;
  type: ButtonTypes | undefined;
};

Working demo

Upvotes: 1

Related Questions