简体   繁体   English

Typescript 说:“类型“a”和“b”没有重叠”。 这是什么意思?

[英]Typescript says: "types '"a"' and '"b"' have no overlap". What does it mean?

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."我想了解这个错误的含义: "types '"a"' and '"b"' have no overlap."

What are they talking about?他们在说什么?

In TypeScript "a" is a literal type .在 TypeScript 中, "a"文字类型 It is a type that has exactly one value, which is "a" .它是一种只有一个值的类型,即"a" Equivalently for "b" .等效于"b"

Due to the way you initialize value TypeScript considers the type of value to be "a" | "b"由于您初始化value的方式 TypeScript 认为value的类型是"a" | "b" "a" | "b" (a union type that basically means the value must be either of type "a" or of type "b" . "a" | "b"联合类型,基本上意味着值必须是"a"类型或"b"类型。

If the type (and therefore also the value) of value is not "a" then the block of the first if will be executed.如果 value 的类型(因此也是value不是"a" ,那么第一个 if 的块将被执行。

That means that the condition of the else if will definitely operate on a value of type (and value) "a" .这意味着else if的条件肯定会对类型(和值) "a"的值进行操作。 Now you are comparing a value of type "a" with a value of type "b" .现在,您将"a"类型的值与"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).但是 TypeScript 中没有值可以同时属于"a"类型和"b"类型,因为类型没有重叠(这只是另一种说法,即没有值可以同时属于两种类型) .

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.换句话说:TypeScript 发现该value此时不能为"b" ,因此else if之后的第二个块永远不会被执行。

As a counter example of types with overlap, consider string and "a" .作为具有重叠类型的反例,请考虑string"a" The value "a" is obviously of type string ."a"显然是string类型。 It is also of type "a" (by definition).也是"a"类型(根据定义)。 That means that the types string and "a" have some overlap .这意味着类型string"a"有一些重叠

In your example, value can only be the string 'a' or 'b' , so:在您的示例中, value只能是字符串'a''b' ,因此:

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' .因此,在这种情况下,无法达到else if (value === 'b')的条件,并且 TypeScript 会阻止您并指定'a' !== 'b'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM