【问题标题】:How do I use an array of strings to be an interface's keys?如何使用字符串数组作为接口的键?
【发布时间】:2021-03-02 01:53:52
【问题描述】:

假设我有这个字符串数组:

const claims = ['val1','val2','val3','val4', ...]

如何根据claims 中的值构建接口,如下所示:

interface Claims {
  val1: boolean
  val2: boolean
  val3: boolean
  val4: boolean
  ...
}

我正在使用 Typescript 3.7.x


我尝试过使用这个答案:https://stackoverflow.com/a/46344193/1439748

interface Claims{
 [key in claims[number]]?: boolean
}

但收到这些错误:

A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1169)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)
'number' only refers to a type, but is being used as a value here.ts(2693)

【问题讨论】:

  • 可以分享游乐场的复制链接吗?

标签: typescript typescript3.8


【解决方案1】:

事实证明,您的代码可以通过进行以下 3 项更改来工作:

  • as const 放在数组字面量之后,以便将 claims 推断为(只读)元组
  • 使用(类型空间)typeof 运算符和claims[number]
  • 代替interface 使用类型别名和对象类型字面量; 事实证明,接口不起作用,而对象类型文字会。

我最终得到了以下代码:

const claims = ['val1','val2','val3','val4'] as const;

type Claims = {
  [key in typeof claims[number]]?: boolean
}

【讨论】:

  • 我将如何在界面本身中执行此操作。如果我尝试在界面中添加[key in typeof claims[number]]?: boolean,我会收到很多错误
猜你喜欢
  • 2017-10-10
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 2018-11-09
  • 1970-01-01
  • 2020-02-28
相关资源
最近更新 更多