Typescript: instanceof check on interface

前端 未结 2 1719
面向向阳花
面向向阳花 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
        }
      }
    }
    

提交回复
热议问题