Cihat Şaman
Cihat Şaman

Reputation: 4824

Why an else if clause results in a "this condition will always return 'true'" error?

One of the topics in the handbook basics is that TypeScript catches logic errors. I changed the else if clause of the if...else statement from the example in the handbook to the following:

const value = Math.random() < 0.5 ? "a" : "b";
if (value !== "a") {

} else if (value !== "b") {
    
}

But got an error:

"This condition will always return 'true' since the types '"a"' and '"b"' have no overlap."

What I am missing? Also, it worked in JavaScript, so why is it not working in TypeScript?

Upvotes: 0

Views: 424

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249796

This is part of control flow analysis and type narrowing.

Typescript will initially type value as "a" | "b". The value !== "a" check means that on the true branch value will be "b" and so it will type value as only "b", on the false branch it will be typed as "a", since anything else would have entered the true branch.

This means that you are checking something which will always be true (value !== b, is always true since value is "a"), and typescript will warn you about it.

Upvotes: 1

Related Questions