4

I have the following type:

type MyType = {
    ['x']?: string;
    ['y']?: number;
} & { [key: string]: string };

When I write this:

const a: MyType = {
    'x': 'str',
    'y': 5
}

I get an error (y is a number while expecting a string) which makes sense according to the index signature. But when I write this:

const b: MyType = {};
b['x'] = 'str2';
b['y'] = 6

It works fine. What is the difference between the two? Should this even work?

4
  • 1
    See this question; the question here isn't exactly a duplicate, but the answer is related. microsoft/TypeScript#17867 might be the canonical issue about this, although there's no great answer in there from anyone who can definitively say if it "should" work to read/write properties whose type conflicts in the two intersection members. ms/TS#37809 is also related. Commented Mar 17, 2021 at 2:17
  • I feel like this is an issue with the ts compiler. I know that MyType shouldn't be written that way, This question is more about the ts compiler. For var a - it behaves like the index signature applies to everything - and you get a contradiction - and therefor an error. For var b - it behaves like the index signature applies to everything other than the x param and y param. so ts is ok with it and you don't get an error. (error for ts compiler) Sounds like a ts compiler bug - or I'm missing something. Commented Mar 17, 2021 at 16:36
  • 1
    Did you look at ms/TS#37809 linked above? Commented Mar 17, 2021 at 17:36
  • Oh Yeah, I missed that link Yeah, Thanks for the help - it is just a built in inconsistent behavior with ts Commented Mar 17, 2021 at 18:13

0

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.