Object destructuring with default empty object generates wrong type
#41.189 geöffnet am 21. Okt. 2020
Repository-Metriken
- Stars
- (48.455 Stars)
- PR-Merge-Metriken
- (Durchschn. Merge 6T 17h) (9 gemergte PRs in 30 T)
Beschreibung
TypeScript Version: 4.0.3
Search Terms:
destructuring object destructuring object destructuring default
Code
const random = () =>
new Date().getTime() % 2 === 0 ? { prop1: 1, prop2: 2, prop3: 3 } : undefined;
const obj = random();
// the type of obj is { prop1: number; prop2: number; prop3: number; } | undefined
const test = { testProp: obj };
const { testProp } = test;
// the type of testProp is { prop1: number; prop2: number; prop3: number; } | undefined
const { testProp: testProp2 = {} } = test;
// the type of testProp2 is: {}
const { prop1 } = obj ?? {}; // works
const { prop2 } = testProp ?? {}; // works
const { prop3 } = testProp2; // error
Expected behavior:
const { prop3 } = testProp2 should work.
Actual behavior:
const { prop3 } = testProp2 returns the error: Property 'prop3' does not exist on type '{}'. ts(2339).
Additional information:
const { prop3 } = testProp2 should work, just like const { prop2 } = testProp ?? {}, because the only difference is that the default {} was assigned during the object destructuring to get testProp2 while, for testProp, the default was assigned during the destructuring of the object itself.
If obj type is Type | undefined, I would expect testProp2 type to be Partial<Type>, as long as Type is not a primitive, but an object (which it is in the above code, so testProp2 should be Partial<{ prop1: number; prop2: number; prop3: number; }>).
Related Issues:
https://github.com/microsoft/TypeScript/issues/41080 (similar, but not the same, already fixed)