[英]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
属性的名称或省略HTMLProps
的size
属性,例如:
type MyHTMLProps = Omit<React.HTMLProps<HTMLAnchorElement>, 'size'>;
export type LinkButtonPropsExtended = ButtonProps & MyHTMLProps;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.