[英]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}`);
}
}
}
它不起作用,因为它不是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.