繁体   English   中英

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

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

为什么以下 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 操场链接

它不起作用,因为它不是never输入过的item ,而是item.type

如果您像这样修改代码,它将起作用:

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

正如@thedude 所说,问题在于您使用的是item而不是item.type

您可以通过尽早从item中获取type然后使用它来纠正问题并使代码更简单; 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`
        }
    }
}

游乐场链接

暂无
暂无

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

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