为什么枚举上的 switch 语句会引发“与类型无法比较"错误? [英] Why does a switch statement on an enum throw 'not comparable to type' error?

查看:15
本文介绍了为什么枚举上的 switch 语句会引发“与类型无法比较"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写有关 Typescript 的 Lynda 教程时(https://www.lynda.com/Visual-Studio-tutorials/TypeScript-types-part-2/543000/565613-4.html#tab ),我遇到了障碍.示例代码说明了 switch 语句在 TypeScript 中是如何工作的,但是对于讲师来说似乎可以正常工作的代码会引发 Type 'x' is not compatible with 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,它只能被赋予该值本身(如果没有严格的空检查,则为空).由于 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 语句会引发“与类型无法比较"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆