如何在 TypeScript 中检查运行时的对象类型? [英] How to check the object type on runtime in TypeScript?

查看:62
本文介绍了如何在 TypeScript 中检查运行时的对象类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to find a way to pass an object to function in and check it type in a runtime. This is a pseudo code:

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 也不起作用并返回相同的内容.

But typeof always returns "object" and I could not find a way to get the real type of a or b. instanceof did not work either and returned the same.

知道如何在 TypeScript 中做到这一点吗?

Any idea how to do it in TypeScript?

推荐答案

编辑:我想向来自搜索的人们指出,这个问题专门针对非类类型,即对象由 interfacetype 别名定义的形状.对于课程类型,您可以使用 JavaScript 的 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.

类型在编译时被剥离,在运行时不存在,所以你不能在运行时检查类型.

Types are stripped away at compile-time and do not exist at runtime, so you can't check the type at runtime.

您可以做的是检查对象的形状是否符合您的预期,并且 TypeScript 可以在编译时使用 用户定义的类型保护 返回真(带注释的返回类型是 arg 形式的类型谓词"是T) 如果形状符合您的期望:

What you can do is check that the shape of an object is what you expect, and TypeScript can assert the type at compile time using a user-defined type guard that returns true (annotated return type is a "type predicate" of the form arg is T) if the shape matches your expectation:

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;
  }
}

游乐场示例

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

How deep you take the type-guard implementation is really up to you, it only needs to return true or false. For example, as Carl points out in his answer, the above example only checks that expected properties are defined (following the example in the docs), not that they are assigned the expected type. This can get tricky with nullable types and nested objects, it's up to you to determine how detailed to make the shape check.

这篇关于如何在 TypeScript 中检查运行时的对象类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆