Intersection types

TypeScript 1.6 introduces intersection types, the logical complement of union types. A union type A | B represents an entity that is either of type A or type B, whereas an intersection type A & B represents an entity that is both of type A and type B.

Example
  1. function extend<T, U>(first: T, second: U): T & U {
  2. let result = <T & U> {};
  3. for (let id in first) {
  4. result[id] = first[id];
  5. }
  6. for (let id in second) {
  7. if (!result.hasOwnProperty(id)) {
  8. result[id] = second[id];
  9. }
  10. }
  11. return result;
  12. }
  13. var x = extend({ a: "hello" }, { b: 42 });
  14. var s = x.a;
  15. var n = x.b;
  1. type LinkedList<T> = T & { next: LinkedList<T> };
  2. interface Person {
  3. name: string;
  4. }
  5. var people: LinkedList<Person>;
  6. var s = people.name;
  7. var s = people.next.name;
  8. var s = people.next.next.name;
  9. var s = people.next.next.next.name;
  1. interface A { a: string }
  2. interface B { b: string }
  3. interface C { c: string }
  4. var abc: A & B & C;
  5. abc.a = "hello";
  6. abc.b = "hello";
  7. abc.c = "hello";

See issue #1256 for more information.