Edit:我想向通过搜索来到这里的人指出,这个问题专门针对非类类型,即对象
类型在编译时被剥离,在运行时不存在,因此不能在运行时判断类型.
您可以做的是判断对象的形状是否符合预期,如果形状符合预期,TypeScript可以在编译时使用返回true的user-defined type guard(带注释的返回类型是arg is T
形式的"类型谓词")断言类型:
interface A {
foo: string;
}
interface B {
bar: number;
}
function isA(obj: any): obj is A {
return obj.foo !== undefined
}
function isB(obj: any): obj is B {
return obj.bar !== undefined
}
function func(obj: any) {
if (isA(obj)) {
// In this block 'obj' is narrowed to type 'A'
obj.foo;
}
else if (isB(obj)) {
// In this block 'obj' is narrowed to type 'B'
obj.bar;
}
}
Example in Playground
类型保护实现的深度取决于您,它只需要返回true或false.例如,正如Carl在回答中指出的那样,上面的示例只判断预期属性是否已定义(遵循文档中的示例),而不是它们是否被分配了预期类型.对于可为空的类型和嵌套对象,这可能会很棘手,由您决定进行形状判断的详细程度.