Unlike classes, interfaces exist only at compile-time, they are not included into the resulting JavaScript, so you cannot do an instanceof
check.
You could make IWalkingAnimal
a subclass of Animal (and use instanceof
), or you could check if the object in question has a walk
method:
if (animal['walk']) {}
You can wrap this in a user defined type guard (so that the compiler can narrow the type when used in an if
statement, just like with instanceof
).
/**
* User Defined Type Guard!
*/
function canWalk(arg: Animal): arg is IWalkingAnimal {
return (arg as IWalkingAnimal).walk !== undefined;
}
private moveAnimal(animal: Animal) {
if (canWalk(animal)) {
animal.walk(); // compiler knows it can walk now
}
}