Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof check on interface

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?

like image 264
Bart van den Burg Avatar asked Jul 31 '15 14:07

Bart van den Burg


2 Answers

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
    }
  }
}
like image 97
Matija Grcic Avatar answered Oct 02 '22 12:10

Matija Grcic


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

if ((<IMyInterfaceA>my).someCoolMethodFromA) {
    (<IMyInterfaceA>my).someCoolMethodFromA();
}
like image 22
Artem Avatar answered Oct 02 '22 13:10

Artem