Skip to content

Iterator result of Iterable or AsyncIterable inferred to any  #33932

Description

@ikokostya

TypeScript Version: 3.7.0-dev.20191010

Search Terms:

Iterable, AsyncIterable, Iterator, IteratorResult

Code

Synchronous iterators:

declareletsyncIterable: Iterable<number>;letres=syncIterable[Symbol.iterator]().next();letvalue=res.value;

Asynchronous iterator:

declareletasyncIterable: AsyncIterable<number>;(async()=>{letres=awaitasyncIterable[Symbol.asyncIterator]().next();letvalue=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:

typeIteratorResult<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

Labels

DuplicateAn existing issue was already created

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions