If you write something like this, you'll get an error.
declare const x: 1 | 2;
if (x === 1) {
// This comparison appears to be unintentional because the types '2' and '1' have no overlap.ts(2367)
} else if (x === 1) {
}
But this is okay.
declare const x: 1 | 2;
if (x === 1) {
} else if (x === 2) {
} else if (x === 1) {
}
If you hover over the x
in the last branch, you'll see its type is set to never
.
What's going on here? You can think of comparisons like these as checking for overlap between sets.
never
is the empty set, which is a subset of every other set. So never
is assignable to anything.
That's why TypeScript doesn't show an error in the last branch.
This solution thanks to mkantor on the TypeScript Discord.