Typescript: 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 "I can not find the name IMyInterfaceA." What is the right way to deal with this situation?

+4
source share
2 answers

It is not possible to check the runtime of the interface because the type information is not translated into compiled JavaScript code.

You can check a specific property or 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 } } } 
+2
source

TypeScript uses duck typing for interfaces, so you just need to check if the object contains specific members:

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

All Articles