admin管理员组

文章数量:1278854

const value = Math.random() < 0.5 ? "a" : "b";
if (value !== "a") {
  // ...
} else if (value === "b") {
This condition will always return 'false' since the types '"a"' and '"b"' have no overlap.

  // Oops, unreachable
}

Found this code in a tutorial. I want to understand the meaning of this error: "types '"a"' and '"b"' have no overlap."

What are they talking about?

const value = Math.random() < 0.5 ? "a" : "b";
if (value !== "a") {
  // ...
} else if (value === "b") {
This condition will always return 'false' since the types '"a"' and '"b"' have no overlap.

  // Oops, unreachable
}

Found this code in a tutorial. I want to understand the meaning of this error: "types '"a"' and '"b"' have no overlap."

What are they talking about?

Share Improve this question asked Apr 21, 2021 at 12:36 Aquarius_GirlAquarius_Girl 22.9k69 gold badges248 silver badges440 bronze badges 2
  • 4 If the value is "b" won't that get captured in the first if? Meaning the second condition can never be hit? – takendarkk Commented Apr 21, 2021 at 12:38
  • 6 Since value can only be a or b, value !== "a" implies value === "b", therefore the else if clause cannot be true since if value === "b" the if branch will be taken. – Nick Commented Apr 21, 2021 at 12:38
Add a ment  | 

2 Answers 2

Reset to default 9

In TypeScript "a" is a literal type. It is a type that has exactly one value, which is "a". Equivalently for "b".

Due to the way you initialize value TypeScript considers the type of value to be "a" | "b" (a union type that basically means the value must be either of type "a" or of type "b".

If the type (and therefore also the value) of value is not "a" then the block of the first if will be executed.

That means that the condition of the else if will definitely operate on a value of type (and value) "a". Now you are paring a value of type "a" with a value of type "b".

But no value in TypeScript can be of type "a" and of type "b" at the same time, since the types have no overlap (which is just another way of saying that no value can be of both types at the same time).

In other words: TypeScript figured out that value can't be "b" at that point and therefore that second block after the else if will never be executed.

As a counter example of types with overlap, consider string and "a". The value "a" is obviously of type string. It is also of type "a" (by definition). That means that the types string and "a" have some overlap.

In your example, value can only be the string 'a' or 'b', so:

if (value !== 'a') {
  // here value can ONLY be 'b'
} else {
  // here value can ONLY be 'a'
}

So in this case, the condition else if (value === 'b') can't be reached and TypeScript prevent you and specify that 'a' !== 'b'.

本文标签: