首页 > 解决方案 > 如何使用字符串数组作为接口的键?

问题描述

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

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)

标签: typescripttypescript3.8

解决方案


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

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

我最终得到以下代码:

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

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

推荐阅读