[英]Typescript throws error with spread operator
我有以下简单的 React 组件:
export interface BadgeProps {
children: React.ReactNode | string | React.ReactNode[],
layout: "gray" | "danger" | "success" | "brand",
size?: "sm" | "base",
}
const Badge: React.FC<BadgeProps> = ({ children }) => {
return (
<div data-test="component-badge">{children}</div>
);
}
当我现在以这种方式调用组件时,它可以正常工作:
<Badge layout="gray">Text</Badge>
但是当我使用扩展运算符传递道具时,出现以下错误。
const props = { layout: "gray" };
return (
<Badge {...props}>Text</Badge>
);
类型“字符串”不可分配给类型“灰色”| “危险” | “成功” | “牌”'
我觉得它应该可以正常工作,但我不知道它为什么会失败。 这是对 Typescript 工作原理的误解吗?
因为"gray" | "danger" | "success" | "brand"
"gray" | "danger" | "success" | "brand"
"gray" | "danger" | "success" | "brand"
是一种特定类型,只能是其中一个字符串,但是当您像这样分配时:
const props = { layout: "gray" };
Typescript 推断layout
属性是字符串而不是您的特殊类型,因此错误。
为了修复此错误,您需要自己标记类型。
export type LayoutType = "gray" | "danger" | "success" | "brand";
export interface BadgeProps {
children: React.ReactNode | string | React.ReactNode[],
layout: LayoutType,
size?: "sm" | "base",
}
const Badge: React.FC<BadgeProps> = ({ children }) => {
return (
<div data-test="component-badge">{children}</div>
);
}
const props: { layout: LayoutType } = { layout: "gray" };
// ------------------------^ your layout type
return (
<Badge {...props}>Text</Badge>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.