As Brian points out, interfaces manifest themselves only at compile time and are used as so-called named-types by the compiler. Section 7 of the language specification describes this as follows:
Interfaces have no run-time representation—they are purely a compile-time construct. Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions.
Further down in section 7.4 of the spec there is a nice description of dynamic type checks in Typescript:
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...
The example in the specification defines three interfaces:
interface Mover {
move(): void;
getStatus(): {speed: number;};
}
interface Shaker {
shake(): void;
getStatus(): {frequency: number;};
}
interface MoverShaker extends Mover, Shaker {
getStatus(): { speed: number; frequency: number; };
}
MoverShaker
combines Mover
and Shaker
into a new compound interface. To validate at runtime that a given type fulfills interface MoverShaker
, you can use Javascript code as follows:
var obj: any = getSomeObject();
if (obj && obj.move && obj.shake && obj.getStatus) {
var moverShaker = <MoverShaker> obj;
...
}
In order to have compile-time checking in Typescript, you need to define interfaces for the types that are exchanged between the two parts of your application. Currently, you have to write dynamic checking code (as above) manually. Hence, static type and dynamic checking code may at some point deviate if you forget to update them in sync. As Brian points out, it would be nice to have a tool that generates the code automatically.