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:
const obj = test ? { text: "hello" } : {}; // { text: string } | { text?: undefined }
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
// let obj: { a: number, b: number } |
// { a: string, b?: undefined } |
// { a?: undefined, b?: undefined }
let obj = [{ a: 1, b: 2 }, { a: "abc" }, {}][0];
obj.a; // string | number | undefined
obj.b; // number | undefined
Multiple object literal type inferences for the same type parameter are similarly collapsed into a single normalized union type:
declare function f<T>(...items: T[]): T;
// let obj: { a: number, b: number } |
// { a: string, b?: undefined } |
// { a?: undefined, b?: undefined }
let obj = f({ a: 1, b: 2 }, { a: "abc" }, {});
obj.a; // string | number | undefined
obj.b; // number | undefined