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

dar*_*phi 5 enums switch-statement logical-operators typescript

我正在尝试打开枚举以便运行正确的代码。我制作了一个打字稿游乐场,展示了我想要实现的目标的一个小例子。

在提供的示例中,我试图理解为什么 Test1 不会打印“B”。我的期望是,当使用逻辑或时,它将尝试检查任一情况是否为真。不只是第一个。这可能是对一些基本原理的误解吗?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
Run Code Online (Sandbox Code Playgroud)

打字稿游乐场

cap*_*ian 3

因为您希望评估结果为 true,所以您应该在语句中EventType.A || EventType.B明确使用。trueswitch


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
Run Code Online (Sandbox Code Playgroud)

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