打字稿:在界面上检查instanceof

Bar*_*urg 12 typescript

给出以下代码:

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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误"找不到名字IMyInterfaceA".处理这种情况的正确方法是什么?

Mat*_*cic 6

由于类型信息未以任何方式转换为已编译的JavaScript代码,因此无法对运行时检查接口.

您可以检查特定属性或方法,并决定要执行的操作.

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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 使用 [`in` 运算符缩小](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing)而不是 `hasOwnProperty` 更为惯用。然后控制流分析/类型推断起作用 - 如果你执行 `if ('isWindowsUser' in myValue) { ... }`,那么在条件内,TS 正确地缩小类型 - 它推断出 `myValue` 实现了 ` IMyInterfaceA`。 (5认同)

Art*_*tem 6

TypeScript对接口使用duck typing,因此您只需检查对象是否包含某些特定成员:

if ((<IMyInterfaceA>my).someCoolMethodFromA) {
    (<IMyInterfaceA>my).someCoolMethodFromA();
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您位于“.tsx”文件中,则“&lt;&gt;”语法将不起作用。另一种方法是使用“as”进行转换:“(my as IMyInterfaceA).someCoolMethodFromA” (3认同)