vendredi 3 novembre 2017

Operator '!==' cannot be applied to types "A" | "B", but '===' can?

I have read Operator '==' cannot be applied to types x and y in Typescript 2 and it has not been informative to my case.

In TypeScript 2.5.3, we define many models using string enums of the form:

export interface Event {
   category: "MORNING" | "NIGHT";
   enabled: boolean;
}

And then apply comparators to them like:

events.filter(event => event.category === 'MORNING');

without complaint.

Now, in this code fragment:

if (event.enabled || event.category === 'MORNING') {
 // something
}
else if (event.category !== 'MORNING') {
 // something else
}

I get the Operator '===' cannot be applied to types '"MORNING"' and '"NIGHT"' compile error in the else if condition, but not in the if condition, which uses the same (but negative) comparator.

Reducing the example further, the following compiles:

if (event.category !== 'MORNING') {
 // something
}
else if (event.category !== 'MORNING') {
 // something else
}

And this compiles:

if (event.category !== 'MORNING') {
 // something
}
else if (event.category === 'MORNING') {
 // something else
}

Whereas this throws an error (in the else if line):

if (event.category === 'MORNING') {
 // something
}
else if (event.category !== 'MORNING') {
 // something else
}

What fundamental property of the type-checker have I misunderstood?

(Note: The final examples are reduced from more complex situations, so I cannot use a simple else.)

Aucun commentaire:

Enregistrer un commentaire