繁体   English   中英

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

[英]Type 'string' is not assignable to type 'undefined'

鉴于这些类型:

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 编译器是否将size属性解释为undefined类型? 为什么?

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

size?: number

这会导致size类型undefined 这是示例typescript 操场,您可以在其中看到类型如何解析为undefined

最好的办法是更改size属性的名称或省略HTMLPropssize属性,例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM