Improved type inference for object literals

TypeScript 2.7 improves type inference for multiple object literals occurring in the same context.When multiple object literal types contribute to a union type, we now normalize the object literal types such that all properties are present in each constituent of the union type.

Consider:

  1. const obj = test ? { text: "hello" } : {}; // { text: string } | { text?: undefined }
  2. const s = obj.text; // string | undefined

Previously type {} was inferred for obj and the second line subsequently caused an error because obj would appear to have no properties.That obviously wasn’t ideal.

Example

  1. // let obj: { a: number, b: number } |
  2. // { a: string, b?: undefined } |
  3. // { a?: undefined, b?: undefined }
  4. let obj = [{ a: 1, b: 2 }, { a: "abc" }, {}][0];
  5. obj.a; // string | number | undefined
  6. obj.b; // number | undefined

Multiple object literal type inferences for the same type parameter are similarly collapsed into a single normalized union type:

  1. declare function f<T>(...items: T[]): T;
  2. // let obj: { a: number, b: number } |
  3. // { a: string, b?: undefined } |
  4. // { a?: undefined, b?: undefined }
  5. let obj = f({ a: 1, b: 2 }, { a: "abc" }, {});
  6. obj.a; // string | number | undefined
  7. obj.b; // number | undefined