Skip to content

Iterator result of Iterable or AsyncIterable inferred to any  #33932

Closed
@ikokostya

Description

@ikokostya

TypeScript Version: 3.7.0-dev.20191010

Search Terms:

Iterable, AsyncIterable, Iterator, IteratorResult

Code

Synchronous iterators:

declare let syncIterable: Iterable<number>;
let res = syncIterable[Symbol.iterator]().next();
let value = res.value;

Asynchronous iterator:

declare let asyncIterable: AsyncIterable<number>;

(async () => {
    let res = await asyncIterable[Symbol.asyncIterator]().next();
    let value = res.value;
});

Expected behavior:

In both cases value has number type.

Actual behavior:

Variable value has any type.


Investigation

Type IteratorResult has two type parameters T and TReturn:

type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;

Because by default TReturn is any (interface Iterable has only one type parameter), we got number | any type, which is narrowed to any.

There are two problems:

  • There is no way to specify TReturn type parameter for IterableIterator and AsyncIterableIterator types.
  • Current behavior is unsafe.

Playground Link:

https://www.typescriptlang.org/play/index.html?ssl=3&ssc=23&pln=1&pc=1#code/CYUwxgNghgTiAEEQBd4GcCeA7MBJZIMUARkgFzz6ElIA8WArgLbGEB8A3AFBKpxrwAvOmx4CRUiADaAZQwsA9hAB0AS3FRkCmAF0AFAEplWEAA9kh7r3gA3KBAYJh-ZXYcgOQA

Related Issues:

#2983

Metadata

Metadata

Assignees

Labels

DuplicateAn existing issue was already created

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions