For the following code:
const x = {
a: 'c',
b: 'd'
};
const y = {
[x.a]: 'e',
}
Run Code Online (Sandbox Code Playgroud)
the generated types are:
typeof x -> {
a: string,
b: string
}
typeof y -> {
[x: string]: string
}
Run Code Online (Sandbox Code Playgroud)
Expected type:
typeof y -> {
c: string
}
Run Code Online (Sandbox Code Playgroud)
Similar issue on SO has a solution which is not relevant here
那是因为typeof x.a实际上是一个字符串。此处,x 是常量,但 的值x.a可以更改为任何字符串值。
如果 的值x.a不会改变,那么一个可能的解决方案(使用typescript 版本 3.4 中添加的const 断言):
const x = {
a: 'c',
b: 'd'
} as const;
const y = {
[x.a]: 'e',
}
typeof y -> {
c: string
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |