Repository navigation
awaited operator doesn't work with type guards #37512
Description
Activity
- addedIn DiscussionNot yet reached consensusNot yet reached consensusSuggestionAn idea for TypeScriptAn idea for TypeScript
on Mar 22, 2020 falsandtru commented
on Mar 23, 2020 ContributorAuthorMore actionsProbably we have to replace isPromiseLike with isAwaited.
if (isPromiseLike(value)) { internal.status = { state: State.resolved, result: value, }; value.then( value => { assert(internal.status.state === State.resolved); internal.status = { state: State.fulfilled, result: value, }; resume(internal); }, reason => { assert(internal.status.state === State.resolved); internal.status = { state: State.rejected, result: reason, }; resume(internal); }); } else { internal.status = { state: State.fulfilled, result: value!, // error }; resume(internal); }
Type 'NonNullable<T>' is not assignable to type 'awaited T'. Type 'T' is not assignable to type 'awaited T'.ts(2322)https://github.com/falsandtru/spica/blob/v0.0.343/src/promise.ts
The problem is that
awaited unknownis just reduced tounknown, so you are asserting thatvalueisunknown. Theawaitedtype does work in type guards:Let me know if that addresses your concerns so that I can close this issue.
falsandtru commented
on Mar 24, 2020 ContributorAuthorMore actionsBasically type arguments are not used in type guards. Can you remove type arguments to accept all types? Actually, your function doesn't accept
T | awaited T | PromiseLike<T>.Ideally, since
Tcan be considered as thenable whenTis notawaited T, isAwaited function should work as follows. Here isAwaited function proves or ensures thatTis just a union ofawaited TandPromiseLike<T>.declare function isAwaited(value: any): value is awaited any; // or awaited typeof value function f<T>(x: T | awaited T | PromiseLike<T>) { if (isAwaited(x)) { x; // awaited T } else { x; // PromiseLike<T> } }
Just to make sure I'm understanding this right, would this be a reasonable implementation of
isAwaited? No matter whatTis,awaited Tis never PromiseLike ("thennable"), sovalue is awaited unknownjust means that value is not PromiseLike.function isAwaited(value: any): value is awaited unknown { return !value || typeof value.then !== "function"; }
awaitedis only preserved when the type argument is generic, soawaited unknownis justunknown. Similar toawaited anyis justany. It's only preserved at higher order.

Ron Buckton (@rbuckton)
TypeScript Version: master
Search Terms:
Code
Expected behavior:
The narrowed type of a is awaited a.
Actual behavior:
The narrowed type of a is a.
Playground Link:
Related Issues: