Extending expressions

TypeScript 1.6 adds support for classes extending arbitrary expression that computes a constructor function. This means that built-in types can now be extended in class declarations.

The extends clause of a class previously required a type reference to be specified. It now accepts an expression optionally followed by a type argument list. The type of the expression must be a constructor function type with at least one construct signature that has the same number of type parameters as the number of type arguments specified in the extends clause. The return type of the matching construct signature(s) is the base type from which the class instance type inherits. Effectively, this allows both real classes and “class-like” expressions to be specified in the extends clause.

Some examples:

  1. // Extend built-in types
  2. class MyArray extends Array<number> { }
  3. class MyError extends Error { }
  4. // Extend computed base class
  5. class ThingA {
  6. getGreeting() { return "Hello from A"; }
  7. }
  8. class ThingB {
  9. getGreeting() { return "Hello from B"; }
  10. }
  11. interface Greeter {
  12. getGreeting(): string;
  13. }
  14. interface GreeterConstructor {
  15. new (): Greeter;
  16. }
  17. function getGreeterBase(): GreeterConstructor {
  18. return Math.random() >= 0.5 ? ThingA : ThingB;
  19. }
  20. class Test extends getGreeterBase() {
  21. sayHello() {
  22. console.log(this.getGreeting());
  23. }
  24. }