Typescript - index signature intersection issue

366 views Asked by At

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?

0

There are 0 answers