Typescript: instanceof check on interface

前端 未结 2 1718
面向向阳花
面向向阳花 2021-01-07 23:12

Given the following code:

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


        
相关标签:
2条回答
  • 2021-01-07 23:58

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

    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
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-08 00:13

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

    if ((<IMyInterfaceA>my).someCoolMethodFromA) {
        (<IMyInterfaceA>my).someCoolMethodFromA();
    }
    
    0 讨论(0)
提交回复
热议问题