Improved union/intersection type inference

TypeScript 1.8 improves type inference involving source and target sides that are both union or intersection types.For example, when inferring from string | string[] to string | T, we reduce the types to string[] and T, thus inferring string[] for T.

Example
  1. type Maybe<T> = T | void;
  2. function isDefined<T>(x: Maybe<T>): x is T {
  3. return x !== undefined && x !== null;
  4. }
  5. function isUndefined<T>(x: Maybe<T>): x is void {
  6. return x === undefined || x === null;
  7. }
  8. function getOrElse<T>(x: Maybe<T>, defaultValue: T): T {
  9. return isDefined(x) ? x : defaultValue;
  10. }
  11. function test1(x: Maybe<string>) {
  12. let x1 = getOrElse(x, "Undefined"); // string
  13. let x2 = isDefined(x) ? x : "Undefined"; // string
  14. let x3 = isUndefined(x) ? "Undefined" : x; // string
  15. }
  16. function test2(x: Maybe<number>) {
  17. let x1 = getOrElse(x, -1); // number
  18. let x2 = isDefined(x) ? x : -1; // number
  19. let x3 = isUndefined(x) ? -1 : x; // number
  20. }