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:

  1. var obj: any = getSomeObject();
  2. if (obj && obj.move && obj.shake && obj.getStatus) {
  3. var moverShaker = <MoverShaker> obj;
  4. ...
  5. }

If such a check is used often it can be abstracted into a function:

  1. function asMoverShaker(obj: any): MoverShaker {
  2. return obj && obj.move && obj.shake && obj.getStatus ? obj : null;
  3. }