7.4 Dynamic Type Checks
TypeScript does not provide a direct mechanism for dynamically testing whether an object implements a particular interface. Instead, TypeScript code can use the JavaScript technique of checking whether an appropriate set of members are present on the object. For example, given the declarations in section 7.1, the following is a dynamic check for the ‘MoverShaker’ interface:
var obj: any = getSomeObject();
if (obj && obj.move && obj.shake && obj.getStatus) {
var moverShaker = <MoverShaker> obj;
...
}
If such a check is used often it can be abstracted into a function:
function asMoverShaker(obj: any): MoverShaker {
return obj && obj.move && obj.shake && obj.getStatus ? obj : null;
}