Local type declarations

Local class, interface, enum, and type alias declarations can now appear inside function declarations. Local types are block scoped, similar to variables declared with let and const. For example:

  1. function f() {
  2. if (true) {
  3. interface T { x: number }
  4. let v: T;
  5. v.x = 5;
  6. }
  7. else {
  8. interface T { x: string }
  9. let v: T;
  10. v.x = "hello";
  11. }
  12. }

The inferred return type of a function may be a type declared locally within the function. It is not possible for callers of the function to reference such a local type, but it can of course be matched structurally. For example:

  1. interface Point {
  2. x: number;
  3. y: number;
  4. }
  5. function getPointFactory(x: number, y: number) {
  6. class P {
  7. x = x;
  8. y = y;
  9. }
  10. return P;
  11. }
  12. var PointZero = getPointFactory(0, 0);
  13. var PointOne = getPointFactory(1, 1);
  14. var p1 = new PointZero();
  15. var p2 = new PointZero();
  16. var p3 = new PointOne();

Local types may reference enclosing type parameters and local class and interfaces may themselves be generic. For example:

  1. function f3() {
  2. function f<X, Y>(x: X, y: Y) {
  3. class C {
  4. public x = x;
  5. public y = y;
  6. }
  7. return C;
  8. }
  9. let C = f(10, "hello");
  10. let v = new C();
  11. let x = v.x; // number
  12. let y = v.y; // string
  13. }