Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic key access in object literal results in widened typescript signature

Tags:

typescript

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

like image 357
Urvashi Gupta Avatar asked Oct 17 '19 10:10

Urvashi Gupta


1 Answers

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
}
like image 103
Harsh Vyas Avatar answered Nov 18 '22 16:11

Harsh Vyas