“字符串”类型不可分配给“未定义”类型

IT技术 reactjs typescript
2021-05-11 01:29:54

鉴于这些类型:

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>
);

这个用例是怎么来的:

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

抛出这种类型的错误:

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>
       |                                        ^

Typescript 编译器是否将 prop 解释size为类型undefined为什么?

1个回答

问题是React.HTMLProps已经有size声明如下的属性:

size?: number

这导致size类型为undefined. 这是typescript playground示例,您可以在其中查看类型是如何解析为的undefined

最好的办法是更改您的size财产名称或省略HTMLProps size财产,例如:

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