Fedoranimus
Fedoranimus

Reputation: 826

Intersection not merging enums for property

I'm trying to create an intersection type in Typescript v2.9.1 where both types have a given property, but of different types: const newItems: A[] & B[] = [];

Given the following interfaces:

export interface A {
    category: EnumA;
}

export interface B {
    category: EnumB;
}

export enum EnumA {
    bar
}

export enum EnumB {
    foo
}

EnumA and EnumB have different values associated with them and I want to be aware of all of those values in a collection.

However if I try to do something like a filter: const filteredItems = newItems.filter(i => i.category !== EnumB.foo);

I'm recieving a syntax error stating Operator '!==' cannot be applied to types 'A' and 'EnumB.foo' and the type of i.category is listed as EnumA in intellisense.

I would expect Typescript understand the type of i.category to be EnumA & EnumB. Is this a bug or do I have unreasonable expectations?

Upvotes: 3

Views: 1495

Answers (1)

Cerberus
Cerberus

Reputation: 10227

It seems you need not an intersection of arrays (A[] & B[], as you've written), because it means "this must have all the properties of Array<A>, and then all the properties of Array<B>, which wasn't listed here before". And since the sets of properties are identical (they are just differently typed), all of them is taken from Array<A>.

The code you used would compile if you write it as following:

const newItems: (A & B)[] = [];
const filteredItems = newItems.filter(i => i.category !== EnumB.foo);

since now the newItems is typed as an "array of things, each of them is both A and B". Their category property is enum, i.e. just object, and so can be merged. Then, we'll have it as enumA & enumB.

Upvotes: 1

Related Questions