Add the 'awaited' type operator by rbuckton · Pull Request #35998 · microsoft/TypeScript · GitHub 您所在的位置:网站首页 condition类型 Add the 'awaited' type operator by rbuckton · Pull Request #35998 · microsoft/TypeScript · GitHub

Add the 'awaited' type operator by rbuckton · Pull Request #35998 · microsoft/TypeScript · GitHub

2023-01-27 22:50| 来源: 网络整理| 查看: 265

It has been over two years since we decided not to move forward with #17077 due to the advent of conditional types, however in that time we have still been unable to devise a reliable mechanism for defining a recursive conditional type that can properly handle the type-side of ECMAScript's await and native Promise unwrapping behavior.

Solutions like Awaited were untenable given that the only way to make the conditional type "recursive" was to introduce complex type like the following:

T extends PromiseLike ? { 0: Awaited }[U extends any ? 0 : never ] : ...

However, there are a number of problems with this approach:

It is not obvious what { 0: ... }[U extends any ? 0 : never] is doing in this alias. The index access type approach is a bit of a "hack" that we probably should not include in our core libs. A self-recursive "promise" type can easily exhaust the maximum recursion limit, resulting in errors in the type alias itself, rather than in the offending code that references it. The quick-info for such a type is non-trivial.

As a result, I would like to reintroduce the awaited type operator from #17077 to meet our needs for a mechanism to recursively unwrap a Promise-like type for methods like Promise.all, Promise.race, Promise.allSettled, Promise.prototype.then, and Promise.prototype.catch. The awaited type operator has the following semantics:

If the type operand is non-generic, the awaited operator is resolved immediately: awaited number is number awaited Promise is number If the type operand is generic, the awaited operator is deferred until instantiated with a non-generic: awaited Promise is awaited T awaited Promise is awaited Obj[K] An awaited S is assignable to an awaited T if S is assignable to T: CAVEAT: This isn't precisely sound, as a non-thenable T could be subtyped with an S that has a then(). However, this is not likely to be a common practice and is no less permissive than the pseudo-recursive conditional type approach. An awaited S is related to T if awaited C is related to T, where C is the constraint of S: function f(x: awaited T) { const y: number = x; // ok, `awaited number` is assignable to `number` }

This will help us to merge PRs such as #33707 without needing to introduce a non-recursive or pseudo-recursive Awaited type.

Fixes: #27711, #31722 Closes: #36435, #36368.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有