【发布时间】:2021-09-24 05:02:37
【问题描述】:
我有这个 React 组件:
const Icon = ({ icon, ...props }: { icon: keyof IconType }) => {
const Icon = Icons[icon]
return <Icon {...props} />
}
我正在尝试以这种方式使用它:
<Icon icon={ordinaryString} />
如何避免出现此打字稿错误:
The type "string" cannot be assigned to the type "keyof IconType".
【问题讨论】:
-
您将需要一个用户定义的类型保护(又名type predicate),以便它返回
str is keyof IconType。然后,TypeScript 将能够推断出保护子句之后的icon必须是IconType的键,而不仅仅是string。
标签: javascript node.js typescript types