o01
o01

Reputation: 5440

Type 'string' is not assignable to type 'undefined'

Given these types:

export type ButtonProps = {
    kind?: 'normal' | 'flat' | 'primary';
    negative?: boolean;
    size?: 'small' | 'big';
    spinner?: boolean;
}

export type LinkButtonPropsExtended = ButtonProps & React.HTMLProps<HTMLAnchorElement>;

const LinkButton = ({ children, href, ...rest }: LinkButtonPropsExtended) => (
    <a href={href} className={cls(rest)}>
        { children }
    </a>
);

How come this use case:

<LinkButton href={url} size="big">My button</LinkButton>

Throws this type error:

64:53 Type 'string' is not assignable to type 'undefined'.
    63 |                 <Button size="big">Another button<Button>
  > 64 |                 <LinkButton href={url} size="big">My button</LinkButton>
       |                                        ^

Is the Typescript compiler interpreting the size prop to be of type undefined? Why?

Upvotes: 4

Views: 2845

Answers (1)

zhuber
zhuber

Reputation: 5524

Problem is that React.HTMLProps already has size property which is declared as following:

size?: number

This causes size type to be undefined. Here is example typescript playground, where you can see how is type resolved to undefined.

Your best bet is to change name of your size property or omit HTMLProps size property, for example:

type MyHTMLProps = Omit<React.HTMLProps<HTMLAnchorElement>, 'size'>;
export type LinkButtonPropsExtended = ButtonProps & MyHTMLProps;

Upvotes: 5

Related Questions