typescript - 枚举上带有或表达式的 Switch case 未按预期计算

标签 typescript enums switch-statement logical-operators

我正在尝试打开枚举以便运行正确的代码。我制作了一个 typescript Playground ,展示了我正在努力完成的事情的一个小例子。

在提供的示例中,我试图理解为什么 Test1 不会打印“B”。我的期望是,当使用逻辑 OR 时,它将尝试检查任一情况是否为真。不只是第一个。这可能是对一些基本原理的误解? Test2 有效,因为我明确说明了案例,但 Test1 将是一个更紧凑的版本。

enum EventType {
    A = "A",
    B = "B",
    C = "C",
}

function Test1(type: EventType) {
    switch(type) {
        case EventType.A || EventType.B:
            console.log("Test1", type);
            break;
        case EventType.C:
            console.log("Test1", type);
            break;

    }
}

function Test2(type: EventType) {
    switch(type) {
        case EventType.A:
        case EventType.B:
            console.log("Test2", type);
            break;
        case EventType.C:
            console.log("Test2", type);
            break;

    }
}

const e = EventType.B;
Test1(e); // Expect "B" to print but does not
Test2(e); // Expect "B" to print and it does

Typescript Playground

最佳答案

因为你期望 EventType.A || EventType.B 评估为 true,您应该在 switch 语句中明确使用 true


enum EventType {
    A = "A",
    B = "B",
    C = "C",
}

function Test1(type: EventType) {
    switch(true) {
        // you should use next approach if you want to mix boolean end enums
        case type === EventType.A || type === EventType.B:
            console.log("Test1", type);
            break;
        case type === EventType.C:
            console.log("Test1", type);
            break;

    }
}

function Test2(type: EventType) {
    switch(type) {
        case EventType.A:
        case EventType.B:
            console.log("Test2", type);
            break;
        case EventType.C:
            console.log("Test2", type);
            break;

    }
}

const e = EventType.B;
Test1(e); // Expect "B" to print and it does it
Test2(e); // Expect "B" to print and it does

像 JS 这样的 TypeScript 没有像 Rust、F#、Reason 等高级 swith 模式......

关于typescript - 枚举上带有或表达式的 Switch case 未按预期计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65934259/

相关文章:

typescript - 如何指定 tsify 的类型路径?

typescript - Angular 2 | NgformControl 阻止我的 NgModel 更新

c# - 在 resharper intellisense 中显示枚举整数值

C++ switch 语句不起作用

c++ - 错误 : switch quantity not an integer

javascript - 如何以不同的名称安装相同的库

reactjs - Next.Js Redux Wrapper w/Typescript - 实现错误,存储类型不存在

android - 如何在TypeConverter中使用Gson将Kotlin枚举与Room存储在一起?

java - 使用基本枚举作为依赖枚举的默认值

c - 没有中断的开关盒是一种不好的做法吗?