Check if an object is an instanceof an interface
April 7, 2020
typescriptinterfaceinstanceof
Checking interface type at runtime
How do you check in typescript if variable is an instance of interface?
Since types are not available at runtime typescript allows you to define type checks that you could use at runtime like:
interface Keyboard {
keys: number;
}
function instanceOfKeyboard(object: any): object is Keyboard {
return 'keys' in object;
}
const kb = { keys: 5 }
if (instanceOfKeyboard(kb)) {
alert(kb.member);
}