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?
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
}
}
}
TypeScript uses duck typing for interfaces, so you should just check if object contains some specific members:
if ((<IMyInterfaceA>my).someCoolMethodFromA) {
(<IMyInterfaceA>my).someCoolMethodFromA();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With