问题描述
在做关于 Typescript 的 Lynda 教程时 (https://www.lynda.com/Visual-Studio-tutorials/TypeScript-types-part-2/543000/565613-4.html#tab ),我遇到了障碍.示例代码说明了 switch 语句在 TypeScript 中是如何工作的,但似乎对教师来说工作正常的代码抛出了一个 Type 'x' 与 type 'y' 不具有可比性的错误.代码如下:
While doing a Lynda tutorial on Typescript ( https://www.lynda.com/Visual-Studio-tutorials/TypeScript-types-part-2/543000/565613-4.html#tab ), I hit a snag. The sample code illustrates how switch statements work in TypeScript but the code that seems to work fine for the instructor throws a Type 'x' is not comparable to type 'y' error. Here's the code:
enum temperature{
cold,
hot
}
let temp = temperature.cold;
switch (temp) {
case temperature.cold:
console.log("Brrr....");
break;
case temperature.hot:
console.log("Yikes...")
break;
}
我收到一个错误并在 case temperature.hot:
下显示:
I get an error and squiggles under case temperature.hot:
saying:
Type 'temperature.hot' is not comparable to type 'temperature.cold'
是什么?
推荐答案
那是因为编译器已经知道情况 temperature.hot
永远不会发生:变量 temp
被赋予枚举文字类型 temperature.cold
,它只能被分配给该值本身(如果没有严格的 null 检查,则为 null).由于 temperature.hot
在这里不是一个兼容的值,编译器会抛出一个错误.
That's because the compiler already knows that the case temperature.hot
will never happen: the variable temp
is given the enum literal type temperature.cold
, which can only be assigned that value itself (or null if there are no strict null checks). As temperature.hot
is not a compatible value here, the compiler throws an error.
如果我们丢弃有关文字的信息(通过强制转换或从函数中检索值):
If we discard the information about the literal (by casting or retrieving the value from a function):
function how_cold(celsius: number): temperature {
return celsius > 40 ? temperature.hot : temperature.cold;
}
代码将编译:
let temp = how_cold(35); // type is "temperature"
switch (temp) {
case temperature.cold:
console.log("Brrr....");
break;
case temperature.hot:
console.log("Yikes...")
break;
}
或者,在值前面加上 +
是有效的,因为它将值转换为数字,这也会扩大类型的范围并使其与所有枚举变体以及其他数字兼容.
Alternatively, prepending +
to the value works because it converts the value to a number, which will also widen the type's scope and make it compatible with all enum variants, as well as other numbers.
let temp = temperature.cold;
switch (+temp) {
case temperature.cold:
console.log("Brrr....");
break;
case temperature.hot:
console.log("Yikes...")
break;
case 5:
console.log("What??");
break;
}
这篇关于为什么枚举上的 switch 语句会抛出“无法与类型相比"的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!