microsoft / microsoft/TypeScript
Object destructuring with default empty object generates wrong type
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
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)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the TypeScript 4.0.3 reproduction in the issue and compare the two destructuring forms, then review related issue #41080 for context. Done means the defaulted testProp2 retains the object properties so that destructuring prop3 no longer reports an error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100