reactjsstyled-componentsreact-propsreact-proptypes

React.HTMLProps<HTMLButtonElement> breaks defaultProps


I had this following code for the PropTypes of my button styled component

export type Props = {
  size?: 'small' | 'medium' | 'large',
};

StyledButton.defaultProps = {
  size: 'medium',
};

It was working fine but then I wanted to include HTMLButtonElement props to provide interactivity to my button. Therefore I added this:

export type Props = React.HTMLProps<HTMLButtonElement> & {
  size?: 'small' | 'medium' | 'large',
};

StyledButton.defaultProps = {
  size: 'medium',
};

However, this change makes defaultProps complains. This is the error, I am getting.

Types of property 'size' are incompatible.
    Type 'string' is not assignable to type 'undefined'.ts(2322)

However, If I take away the React.HTMLProps, it works, but that's not what I want. Does anybody know a solution for this?

Thanks in advance.


Solution

  • I think you have to define a new interface:

    export interface Props extends React.HTMLProps<HTMLButtonElement> {
      size?: 'small' | 'medium' | 'large',
    };
    

    The problem is that React.HTMLProps or rather, its superinterface HTMLAttributes already contains a size attribute defined as:

    size?: number;
    

    Therefore, you will have to rename your property.