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
TypeScript Version: 3.7.0-dev.20191010
Search Terms:
Iterable, AsyncIterable, Iterator, IteratorResult
Code
Synchronous iterators:
Asynchronous iterator:
Expected behavior:
In both cases
valuehasnumbertype.Actual behavior:
Variable
valuehasanytype.Investigation
Type
IteratorResulthas two type parametersTandTReturn:TypeScript/lib/lib.es2015.iterable.d.ts
Line 41 in 6162001
Because by default
TReturnisany(interfaceIterablehas only one type parameter), we gotnumber | anytype, which is narrowed toany.There are two problems:
TReturntype parameter forIterableIteratorandAsyncIterableIteratortypes.Playground Link:
https://www.typescriptlang.org/play/index.html?ssl=3&ssc=23&pln=1&pc=1#code/CYUwxgNghgTiAEEQBd4GcCeA7MBJZIMUARkgFzz6ElIA8WArgLbGEB8A3AFBKpxrwAvOmx4CRUiADaAZQwsA9hAB0AS3FRkCmAF0AFAEplWEAA9kh7r3gA3KBAYJh-ZXYcgOQA
Related Issues:
#2983