Async for loop falling back to Iterable<T_Sync> even if object implements AsyncIterable<T_Async>.
Closed this issue ยท 1 comments
zhangyx1998 commented
๐ Search Terms
AsyncIterablefor await
๐ Version & Regression Information
- This changed between versions N/A and N/A
- This changed in commit or PR N/A
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
- I was unable to test this on prior versions because _______
โฏ Playground Link
๐ป Code
type Stream<T_Sync, T_Async> = Iterable<T_Sync> & AsyncIterable<T_Async>
class A {};
class B {};
async function loop(stream: Stream<A, B>) {
// ok: variable `a` is of type `A`
for (const a of stream) {}
// Bad: variable `b` should be of type `B`, TS asserted `A`
for await (const b of stream) {}
}๐ Actual behavior
TS asserts b of type A even if stream implements AsyncIterable<B>.
๐ Expected behavior
b should be asserted to type B.
Additional information about the issue
Related issue #36153 discussed adding a type helper ForAwaitable for types support either sync or async iteration. However, the OP does not cover the issue that TS should prefer AsyncIterable<T> in async for loop when possible.
Andarist commented
This is a caching issue: TS playground