对象文字中的动态键访问导致打字稿签名扩大

时间:2019-10-17 10:45:28

标签: typescript

对于以下代码:

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,该消息说这是固定的,但不起作用

1 个答案:

答案 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
}