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
orb
,value !== "a"
impliesvalue === "b"
, therefore theelse if
clause cannot be true since ifvalue === "b"
the if branch will be taken. – Nick Commented Apr 21, 2021 at 12:38
2 Answers
Reset to default 9In 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'
.
本文标签:
版权声明:本文标题:javascript - Typescript says: "types '"a"' and '"b"' 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741278758a2369885.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论