如何使用字符串数组作为接口的键?

How do I use an array of strings to be an interface's keys?

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

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

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

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

我正在使用 Typescript 3。7.x


我试过这个答案:

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)

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

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

我得到了以下代码:

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

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