microsoft / microsoft/TypeScript
Implicit Symbol.iterator call in for..of loops / spread destructuring doesn't infer `this` generic type parameter
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.0-dev.20200507
Search Terms: Symbol.iterator type parameter implicit calling for..of loops object spread destructuring this generic
Code
What follows is 3 different ways of iterating over an object using a custom-made iterator. However, using Symbol.iterator implicitly via the for..of loop fails to produce the same behavior:
const obj = {
x: 1,
y: 2,
z: 3,
*[Symbol.iterator]<T extends object>(
this: T,
): Generator<NonNullable<{ [K in keyof T]: [K, NonNullable<T[K]>] }[keyof T]>, void, unknown> {
for (const entry of Object.entries(this)) yield entry as never;
},
};
{
const iter = obj[Symbol.iterator]();
for (let result = iter.next(); !result.done; result = iter.next()) {
const { value } = result;
value; // ["x", number] | ["y", number] | ["z", number]
}
}
for (const value of obj[Symbol.iterator]()) {
value; // ["x", number] | ["y", number] | ["z", number]
}
for (const value of obj) {
value; // NonNullable<{ [K in keyof T]: [K, NonNullable<T[K]>]; }[keyof T]>
// bad! This should be ["x", number] | ["y", number] | ["z", number]
}
// also, spread destructuring suffers from the same problem!
const values = [...obj]; // Array<NonNullable<{ [K in keyof T]: [K, NonNullable<T[K]>]; }[keyof T]>>
// bad! This should be Array<["x", number] | ["y", number] | ["z", number]>
Expected behavior: for (const value of obj) should implicitly do the type equivalent of calling our iterator symbol, i.e. for (const value of obj[Symbol.iterator]()). That means our type parameter should be correctly inferred like so: obj[Symbol.iterator]<T>(this: T).
Actual behavior: T cannot be inferred as the local this type, so all derivative types cannot be evaluated and the type stays as its generic version.
Related Issues: n/a
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
Reproduce the issue using the provided TypeScript code or Playground Link, comparing explicit Symbol.iterator calls with for..of and spread destructuring. Trace the compiler's handling of implicit iterator calls and generic this inference; done means both implicit forms infer the same tuple union as the explicit calls.
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