【问题标题】:How to use partially the computed property name on a type definition如何在类型定义上部分使用计算的属性名称
【发布时间】:2020-01-06 11:34:11
【问题描述】:

我需要为接收 prop name(应该是 Fields 的值)和任何其他 props 的 React 组件定义类型。

所以我尝试了类似的方法

type Fields = 'address' | 'recipientName' | 'recipientPhone';

type Props = {
  name: Fields
  [key in string]: any // error here
};

但它不起作用。我收到此错误:

类型文字中的计算属性名称必须引用其类型为文字类型或“唯一符号”类型的表达式。

如何创建这种类型?

【问题讨论】:

  • [key in string]改成[key: string]?

标签: typescript typescript-typings


【解决方案1】:

您使用的是mapped types 语法,而不是普通的字典语法。试试这个:

type Fields = 'address' | 'recipientName' | 'recipientPhone';

type Props = {
  name: Fields
  [key: string]: any // All good
};

这可能就是您正在寻找的。但是,如果您出于某种原因确实想使用映射类型以及单独的键,则需要定义两种类型并将它们相交,如下所示:

type Fields = 'address' | 'recipientName' | 'recipientPhone';

type Props = {
  name: Fields
} & {
  [key in string]: any // All good
};

只有当key in stringany 变得更复杂时,您才需要这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 2015-10-08
    • 2021-07-07
    • 1970-01-01
    • 2018-04-13
    • 2018-11-23
    • 1970-01-01
    相关资源
    最近更新 更多