简体   繁体   English

为什么此 TypeScript 详尽的开关检查不起作用?

[英]Why is this TypeScript exhaustive switch check not working?

Why does the following switch default case not lead to an exhaustive check where item is correctly identified as never?为什么以下 switch 默认情况不会导致彻底检查项目被正确识别为从不?

enum Type {
    First,
    Second
}

interface ObjectWithType {
    type: Type;
}

const array: ObjectWithType[] = [];

for (const item of array) {
    switch (item.type) {
        case Type.First:
            break;
        case Type.Second:
            break;
        default: {
            const unhandledItem: never = item;
            throw new Error(`Unhandled type for item: ${unhandledItem}`);
        }
    }
}

Typescript playground link Typescript 操场链接

It's not working because it's not the item that has never type, it's the item.type .它不起作用,因为它不是never输入过的item ,而是item.type

If you modify your code like so, it will work:如果您像这样修改代码,它将起作用:

const unhandledItem: never = item.type;
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^

As @thedude said, the problem is that you're using item instead of item.type .正如@thedude 所说,问题在于您使用的是item而不是item.type

You can correct the problem and make the code simpler by grabbing type from item early and then using that;您可以通过尽早从item中获取type然后使用它来纠正问题并使代码更简单; in the default , the type of type will automatically be narrowed to never : default ,类型的type将自动缩小为never

for (const item of array) {
    const {type} = item;
    switch (type) {
        case Type.First:
            break;
        case Type.Second:
            break;
        default: {
            throw new Error(`Unhandled type for item: ${type}`);
            // The type here is automatically narrowed  ^^^^  to `never`
        }
    }
}

Playground link 游乐场链接

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

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