Mar*_*nte 7 types instanceof typescript
我正在尝试检查变量是否属于某种类型。
代码:
type GeneralType = SubTypeA | SubTypeB;
type SubTypeA = 'type1' | 'type2';
type SubTypeB = 'type3' | 'type4';
function someFunction(arg1: GeneralType) {
if (arg1 instanceof SubTypeA) {
// Do something
}
// Continue function
return arg1;
}
Run Code Online (Sandbox Code Playgroud)
当然,这段代码在第 6 行失败了,因为instanceof它不能用于类型。有没有我可以使用的替代选项,而无需明确检查 的每个可能值SubTypeA?
正如评论中提到的,似乎没有简单的方法可以实现这一点。
最后,我发现最优雅的方法是使用类型保护,如下所示:
type GeneralType = SubTypeA | SubTypeB;
type SubTypeA = 'type1' | 'type2';
type SubTypeB = 'type3' | 'type4';
function someFunction(arg1: GeneralType) {
if (isSubTypeA(arg1)) {
// Do something
}
// Continue function
}
function isSubTypeA(arg: GeneralType): arg is SubTypeA {
return ['type1', 'type2'].some(element => element === arg);
}
Run Code Online (Sandbox Code Playgroud)
更详细的解释可以在这里找到。