Skip to content

IteratorResult<T> definition conflicts with the JS spec #38479

Closed
@ldantonov

Description

@ldantonov

TypeScript Version: 3.8.3

Search Terms: iterator return type

Code

const list = ['v1', 'v2', 'v3']

const f: () => Iterator<string> = () => {
  let index = 0
  return {
    next: (): IteratorResult<string> => {
      console.log(list)
      if (index < list.length) {
        return { value: list[index++]}
      } else {
        return { done: true }
      }
    }
  }
}

Expected behavior:
The code should compile without errors.
Actual behavior:
The code compiles with the error: "Type '{ done: true; }' is not assignable to type 'IteratorResult<string, any>'.
Property 'value' is missing in type '{ done: true; }' but required in type 'IteratorReturnResult'.(2322)"

The error can be bypassed by changing { done: true } to { value: undefined, done: true }. However, the specification allows omitting the value property. See Iteration Protocols

A suggested fix would be to change the definition of the type IteratorReturnResult to:

interface IteratorReturnResult<TReturn> {
    done: true;
    value?: TReturn;
}

Playground Link: https://www.typescriptlang.org/play?#code/MYewdgzgLgBANgS2jAvDA2gcgG4EZMA0MOATIcdgMyYC6AUHaJLAGYBcMAFAJSoB8MAJJQApgCcAhlBBiAPNDEIwAcwFoe-GAG86MeCNhKAJiIAeqGAAZdMMQYCuYsNpt6wZqBx4dh4qTIAlEQh7OCh5KEUVNQEdPXiYJggQOBEAOjgQZU5EaG5XeIQWLmMzGFl4JCgMkRUoAAteOIT4uyhHZy0YbAk4exEOXKh0UtMAajGaAF8CvSmYETgIERcW1ocnbRgjcAGYSP6YGbXj+NOZqaA

Related Issues:
#29982

Metadata

Metadata

Assignees

Labels

Design LimitationConstraints of the existing architecture prevent this from being fixedRescheduledThis issue was previously scheduled to an earlier milestoneWorking as IntendedThe behavior described is the intended behavior; this is not a bug

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions