【问题标题】:Typeof/instanceof type aliastypeof/instanceof 类型别名
【发布时间】:2021-09-18 01:16:47
【问题描述】:

我想知道是否可以在打字稿中确定对象的类型。请考虑以下示例:

type T = [number, boolean];

class B {
    foo: T = [3, true];

    bar(): boolean {
        return this.foo instanceof T;
    }
}

typeof 运算符似乎不是一个解决方案,instanceof 也不是。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    简答

    (几乎)所有类型信息在编译后都会被删除,并且您不能将instanceof 运算符与在运行时不存在的操作数(在您的示例中为T)一起使用。

    长答案

    TypeScript 中的标识符可以属于以下一组或多组:typevaluenamespace。作为 JavaScript 发出的是 value 组中的标识符。

    因此,运行时运算符仅适用于 。因此,如果您想对 foo 的值进行运行时类型检查,您需要自己完成这项艰苦的工作。

    有关详细信息,请参阅 TypeScript 手册的 Declaration Merging 部分。

    【讨论】:

      【解决方案2】:

      添加到 @vilcvane 的答案:typesinterfaces 在编译过程中消失,但一些 class 信息仍然可用。因此,例如,这不起作用:

      interface MyInterface { }
      
      var myVar: MyInterface = { };
      
      // compiler error: Cannot find name 'MyInterface'
      console.log(myVar instanceof MyInterface);
      

      但这确实:

      class MyClass { }
      
      var myVar: MyClass = new MyClass();
      
      // this will log "true"
      console.log(myVar instanceof MyClass);
      

      但是,重要的是要注意这种测试可能会产生误导,即使您的代码编译时没有错误:

      class MyClass { }
      
      var myVar: MyClass = { };
      
      // no compiler errors, but this logs "false"
      console.log(myVar instanceof MyClass);
      

      This makes sense if you look at how TypeScript is generating the output JavaScript in each of these examples

      【讨论】:

      • 类仍然存在,因为一个类同时属于 valuetype 组。在第二个示例中,另一个关键是 TypeScript 根据类型的“形状”进行类型检查。虽然 GitHub 上有关于名义类型的讨论:github.com/Microsoft/TypeScript/issues/202
      猜你喜欢
      • 2018-10-13
      • 2013-01-28
      • 2016-01-30
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 2010-12-26
      相关资源
      最近更新 更多