typescript - 如何在 TypeScript 中检查运行时的对象类型?

标签 typescript types runtime

我正在尝试找到一种方法来传递一个对象以在运行时运行并检查它的类型。这是一个伪代码:

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" 而我找不到获取 ab 的真实类型的方法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 or type alias. For class types you can use JavaScript's instanceof 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;
  }
}

Example in Playground

你对类型保护实现的深入程度完全取决于你,它只需要返回 true 或 false。例如,正如 Carl 在他的回答中指出的那样,上面的示例仅检查是否定义了预期的属性(按照文档中的示例),而不是检查是否为它们分配了预期的类型。对于可空类型和嵌套对象,这可能会变得棘手,由您决定进行形状检查的详细程度。

关于typescript - 如何在 TypeScript 中检查运行时的对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44078205/

相关文章:

java - 如何在 OpenScript - Oracle Application Testing Suite 中传递运行时参数?

javascript - Angular 6 : How to prevent 2 subscribed variables in one Observable from cascading each other

java - 如何使用有界类型参数扩展泛型类

oracle - 在 Oracle 中,如何验证对象类型层次结构中使用的对象类型?

c++ - 不相关类型的动态调度解决方案

java - 动态规划 - 什么是渐近运行时?

javascript - 在工作线程之间共享负载的最佳方式

javascript - Typescript - 从我的函数中删除样板文件

angular - 测试使用 templateUrl 的组件时出错

Scala - 发现类型不匹配的单元 : required Array[Int]