6

For the following code:

const x = {
    a: 'c',
    b: 'd'
};

const y = {
    [x.a]: 'e',
}

the generated types are:

typeof x -> {
    a: string,
    b: string
}

typeof y -> {
  [x: string]: string
}

Expected type:

typeof y -> {
  c: string
}

Similar issue on SO has a solution which is not relevant here

Found the reported issue on Github which says this was fixed but is somehow not working

Urvashi Gupta
  • 270
  • 1
  • 7

1 Answers1

4

That's because typeof x.a is actually a string. Here, x is constant but the value of x.a can be changed to any string value.

If the value of x.a is not going to change then a possible solution(using const assertion added in typescript version 3.4):

const x = {
    a: 'c',
    b: 'd'
} as const;

const y = {
    [x.a]: 'e',
}

typeof y -> {
    c: string
}
Harsh Vyas
  • 56
  • 4