Interfaces

Interfaces have zero runtime JS impact. There is a lot of power in TypeScript interfaces to declare the structure of variables.

The following two are equivalent declarations, the first uses an inline annotation, the second uses an interface:

  1. // Sample A
  2. declare var myPoint: { x: number; y: number; };
  3. // Sample B
  4. interface Point {
  5. x: number; y: number;
  6. }
  7. declare var myPoint: Point;

However the beauty of Sample B is that if someone authors a library that builds on the myPoint library to add new members, they can easily add to the existing declaration of myPoint:

  1. // Lib a.d.ts
  2. interface Point {
  3. x: number; y: number;
  4. }
  5. declare var myPoint: Point;
  6. // Lib b.d.ts
  7. interface Point {
  8. z: number;
  9. }
  10. // Your code
  11. var myPoint.z; // Allowed!

This is because interfaces in TypeScript are open ended. This is a vital tenet of TypeScript that it allows you to mimic the extensibility of JavaScript using interfaces.

Classes can implement interfaces

If you want to use classes that must follow an object structure that someone declared for you in an interface you can use the implements keyword to ensure compatibility:

  1. interface Point {
  2. x: number; y: number;
  3. }
  4. class MyPoint implements Point {
  5. x: number; y: number; // Same as Point
  6. }

Basically in the presence of that implements, any changes in that external Point interface will result in a compile error in your code base so you can easily keep it in sync:

  1. interface Point {
  2. x: number; y: number;
  3. z: number; // New member
  4. }
  5. class MyPoint implements Point { // ERROR : missing member `z`
  6. x: number; y: number;
  7. }

Note that implements restricts the structure of the class instances i.e.:

  1. var foo: Point = new MyPoint();

And stuff like foo: Point = MyPoint is not the same thing.

TIPs

Not every interface is implementable easily

Interfaces are designed to declare any arbitrarily crazy structure that might be present in JavaScript.

Consider the following interface where something is callable with new:

  1. interface Crazy {
  2. new (): {
  3. hello: number
  4. };
  5. }

You would essentially have something like:

  1. class CrazyClass implements Crazy {
  2. constructor() {
  3. return { hello: 123 };
  4. }
  5. }
  6. // Because
  7. const crazy = new CrazyClass(); // crazy would be {hello:123}

You can declare all the crazy JS out there with interfaces and even use them safely from TypeScript. Doesn’t mean you can use TypeScript classes to implement them.