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

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! But to note, this will work with version 3.4 and above. For older ones, we will have to do something like: const x = { a: 'c' as 'c', b: 'd' as 'd' }. Could you please update the answer to reflect the version information?
Thanks, I will do it.
@HarshVyas Your edit introduced a typo: you mean v 3.4 not 4.3!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.