【问题标题】:How can I properly type this?我怎样才能正确输入这个?
【发布时间】: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


【解决方案1】:

我将假设 ordinaryStringstring 类型,因为这就是错误消息的内容。

问题是你提供了一个字符串,它可以是任何东西,但组件需要keyof IconType,它不能是任何字符串,但必须是与IconType 中的一个键匹配的字符串.

要么提供匹配keyof IconType(或使用keyof IconType 键入的变量/常量)的字符串文字,将组件中icon 属性的类型更改为string(但要注意后一个选项将意味着@ 987654329@ 需要可以按字符串索引)。

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 2015-02-07
    • 2022-11-01
    • 2021-02-10
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多