Dynamic key access in object literal results in widened typescript signature

Urv*_*pta 5 typescript

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

在Github上发现了已举报的问题,该问题已解决,但无法正常工作

Har*_*yas 4

那是因为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)