我可以使用包含变量的模板文字作为对象键吗?

Can I use a template literal containing a variable as an object key?

我希望下面的代码可以工作,但我不确定为什么它不工作:

interface Person {
  firstName: string
}

const property: 'Name' = 'Name'

const zack: Person = {
  [`first${property}`]: 'Zack'
}

创建 zack 引发错误:

Property 'firstName' is missing in type '{ [x: string]: string; }' but required in type 'Person'.

再试一下,任何字符串连接似乎都是问题所在:

type EqualsFirstName = 'firstName'

const value: EqualsFirstName = 'first' + 'Name'

那也不行。

这个 hack 可能会奏效

interface Person {
  firstName: string
}

const property: 'Name' = 'Name'
type EqualsFirstName = 'firstName'

const zack: Person = {
  [`first${property}` as EqualsFirstName]: 'Zack'
}

TypeScript 编译器在评估映射类型时相当严格。有很多事情不能很好地与他们合作,这就是其中之一。它在您断言类型时有效:

const zack: Person = {
    [`first${property}` as 'firstName']: 'Zack'
}

尽管如以下代码所示,这并不是很有帮助,它也可以正常编译,但在运行时会失败:

const property: 'Foo' = 'Foo'

const zack: Person = {
  [`first${property}` as 'firstName']: 'Zack'
}

另一个(有点笨拙)选项是用 as 断言类型 Person(然后先断言到 unknown):

const zack = {
  [`first${property}`]: 'Zack'
} as unknown as Person

与第一个选项一样,如果断言无效,这在运行时将无济于事。

我建议您尝试不使用这种表示法,而选择更 "TS compiler friendly" 的方式。这是一个非常不寻常的构造,在技术上是有效的,但在实践中你宁愿避免。