typescript 打字稿:instanceof 检查接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31748277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:03:30  来源:igfitidea点击:

Typescript: instanceof check on interface

typescript

提问by Bart van den Burg

Given the following code:

鉴于以下代码:

module MyModule {
  export interface IMyInterface {}
  export interface IMyInterfaceA extends IMyInterface {}
  export interface IMyInterfaceB extends IMyInterface {}

  function(my: IMyInterface): void {
    if (my instanceof IMyInterfaceA) {
      // do something cool
    }
  }
}

I get the error "Can't find name IMyInterfaceA". What's the correct way to handle this situation?

我收到错误“找不到名称 IMyInterfaceA”。处理这种情况的正确方法是什么?

采纳答案by Matija Grcic

There is no way to runtime check an interface as type information is not translated in any way to the compiled JavaScript code.

无法运行时检查接口,因为类型信息不会以任何方式转换为已编译的 JavaScript 代码。

You can check for a specific property or a method and decide what to do.

您可以检查特定的属性或方法并决定要做什么。

module MyModule {
  export interface IMyInterface {
      name: string;
      age: number;
  }
  export interface IMyInterfaceA extends IMyInterface {
      isWindowsUser: boolean;
  }
  export interface IMyInterfaceB extends IMyInterface {

  }

  export function doSomething(myValue: IMyInterface){
    // check for property
    if (myValue.hasOwnProperty('isWindowsUser')) {
      // do something cool
    }
  }
}

回答by Artem

TypeScript uses duck typing for interfaces, so you should just check if object contains some specific members:

TypeScript 对接口使用鸭子类型,因此您应该只检查对象是否包含某些特定成员:

if ((<IMyInterfaceA>my).someCoolMethodFromA) {
    (<IMyInterfaceA>my).someCoolMethodFromA();
}