Tomas Ovesny Tomas Ovesny -4 years ago 73
TypeScript Question

Explanation of Typescript's intersection types

i was playing around with intersection types and i would expect following as working?

Could someone shed some light on it?

type SomeError = {
message: string;
code?: number;
};

type SomeResponse = {
error: SomeError & { code: string; }
};

const response: SomeResponse = {
error: {
message: 'neco',
code: 'a'
}
};

// Type 'string' is not assignable to type 'number'.

const response2: SomeResponse = {
error: {
message: 'neco',
code: 50
}
};

// Type 'number' is not assignable to type 'string'.

Answer Source

The issue is that SomeResponse has this type for code:

number & string

And that's impossible to have.

You can check that this is the case quite easily in playground with your code:

let test = response.error.code;

The type of test is number & string (just hover over the variable name)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download