Skip to content

Trouble implementing AsyncIterator interface in 3.6.2 #33239

Closed
@brainkim

Description

@brainkim

TypeScript Version: 3.6.2

Search Terms:
async iterator iterable next

Code:
filename: constant.ts

class ConstantIterator<T> implements AsyncIterator<T, undefined, T | undefined> {
  constructor(private constant: T) {
  }
  async next(value?: T): Promise<IteratorResult<T>> {
    if (value != null) {
      throw new Error("ConstantIterator.prototype.next may not take any values");
    }
    return {value: this.constant, done: false};
  }
}

Expected behavior:
Code compiles.
Actual behavior:

constant.ts(4,9): error TS2416: Property 'next' in type 'ConstantIterator<T>' is not assignable to the same property in base type 'AsyncIterator<T, undefined, T>'.
  Type '(value?: T) => Promise<{ value: T; done: boolean; }>' is not assignable to type '(...args: [] | [T | PromiseLike<T>]) => Promise<IteratorResult<T, undefined>>'.
    Types of parameters 'value' and 'args' are incompatible.
      Type '[] | [T | PromiseLike<T>]' is not assignable to type '[T?]'.
        Type '[T | PromiseLike<T>]' is not assignable to type '[T?]'.
          Types of property '0' are incompatible.
            Type 'T | PromiseLike<T>' is not assignable to type 'T'.
              'T | PromiseLike<T>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.
                Type 'PromiseLike<T>' is not assignable to type 'T'.
                  'PromiseLike<T>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.

Note that the synchronous version of ConstantIterator does not throw the same error. It’s the type union of T | PromiseLike<T> which seems to cause the error.

Playground Link:
Playground has yet to be updated for 3.6.

Related Issues:
#30790 Strongly typed iterator PR.
#32682 Other (async) iterator usability issues.
#33131 Possible change to type inference in 3.6.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptDomain: lib.d.tsThe issue relates to the different libraries shipped with TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions