对于以下代码:
const x = {
a: 'c',
b: 'd'
};
const y = {
[x.a]: 'e',
}
生成的类型为:
typeof x -> {
a: string,
b: string
}
typeof y -> {
[x: string]: string
}
预期类型:
typeof y -> {
c: string
}
SO上类似的issue有一个与此处无关的解决方案
在Github上找到了报道的issue,该消息说这是固定的,但不起作用
答案 0 :(得分:3)
这是因为typeof x.a
实际上是一个字符串。这里,x是常数,但是x.a
的值可以更改为任何字符串值。
如果x.a
的值不会改变,那么可能的解决方案(使用在打字稿版本3.4中添加的const assertion):
const x = {
a: 'c',
b: 'd'
} as const;
const y = {
[x.a]: 'e',
}
typeof y -> {
c: string
}