我正在尝试找到一种方法来传递一个对象以在运行时运行并检查它的类型。这是一个伪代码:
function func (obj:any) {
if(typeof obj === "A") {
// do something
} else if(typeof obj === "B") {
//do something else
}
}
let a:A;
let b:B;
func(a);
但是 typeof
总是返回 "object"
而我找不到获取 a
或 b 的真实类型的方法
。 instanceof
也没有工作并返回相同的结果。
知道如何在 TypeScript 中做到这一点吗?
最佳答案
Edit: I want to point out to people coming here from searches that this question is specifically dealing with non-class types, ie object shapes as defined by
interface
ortype
alias. For class types you can use JavaScript'sinstanceof
to determine the class an instance comes from, and TypeScript will narrow the type in the type-checker automatically.
类型在编译时被剥离,在运行时不存在,因此您无法在运行时检查类型。
您可以做的是检查对象的形状是否符合您的预期,TypeScript 可以在编译时使用 user-defined type guard 断言类型。如果形状符合您的期望,则返回 true(带注释的返回类型是 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;
}
}
你对类型保护实现的深入程度完全取决于你,它只需要返回 true 或 false。例如,正如 Carl 在他的回答中指出的那样,上面的示例仅检查是否定义了预期的属性(按照文档中的示例),而不是检查是否为它们分配了预期的类型。对于可空类型和嵌套对象,这可能会变得棘手,由您决定进行形状检查的详细程度。
关于typescript - 如何在 TypeScript 中检查运行时的对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44078205/