【问题标题】:How to use union type as property name of interface/type如何使用联合类型作为接口/类型的属性名称
【发布时间】:2019-11-26 18:35:03
【问题描述】:

我有一个联合类型:

type Browser = 'chrome' | 'firefox'

我想创建一个接口/类型,其中有效属性只能是 chrome 和 firefox。我想出了这个:

type IM {
  [key in Browser]: {
    string: boolean
  }
}

问题是我希望允许 chromefirefox 属性中的任何属性。可能吗?我试图使用括号概念:

[string]: boolean

但不出所料,它不起作用。

【问题讨论】:

  • 类型浏览器 = 'chrome' | '火狐' |字符串;

标签: typescript types interface


【解决方案1】:

如果您想允许任何boolean 属性,您可以使用索引签名:

type Browser = 'chrome' | 'firefox'

type IM = {
  [key in Browser]: {
    [name: string]: boolean
  }
}

自定义映射类型不是必须的,你可以使用Record代替:

type IM = Record<Browser, {
    [name: string]: boolean
}>

【讨论】:

    猜你喜欢
    • 2022-10-06
    • 2021-01-12
    • 1970-01-01
    • 2017-09-16
    • 2020-10-02
    • 2019-09-22
    • 2018-11-23
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多