如何解开 Promise 的类型 [英] How to Unwrap Type of a Promise
问题描述
假设我有以下代码:
async promiseOne() {
return 1
} // => Promise<number>
const promisedOne = promiseOne()
typeof promisedOne // => Promised<number>
我将如何提取承诺结果的类型(在这种简化的情况下是一个数字)作为它自己的类型?
How would I go about extracting the the type of the promise result (in this simplified case a number) as it's own type?
推荐答案
截至 Typescript 2.8,现在可以利用 条件类型的,这里有一个基本的示例:游乐场
As of Typescript 2.8, this is now possible by taking advantage of conditional types, here's a basic example: Playground
function promiseOne() {
return Promise.resolve(1)
}
const promisedOne = promiseOne()
// note PromiseLike instead of Promise, this lets it work on any thenable
type ThenArg<T> = T extends PromiseLike<infer U> ? U : T
type PromiseOneThenArg = ThenArg<typeof promisedOne> // => number
// or
type PromiseOneThenArg2 = ThenArg<ReturnType<typeof promiseOne>> // => number
这不是一个完美的解决方案.承诺不能包含其他承诺.Promise
不是真实的,如果你 await
得到的类型应该是 string
,但是 ThenArg
将给出 Promise
.
This isn't a perfect solution. Promises cannot contain other promises. Promise<Promise<string>>
isn't real, and the type you get if you await
it should be string
, but ThenArg
will give Promise<string>
.
TypeScript 4.1 包括对递归类型别名的支持,这使得编写以下内容成为可能.游乐场
TypeScript 4.1 includes support for recursive type aliases, which makes it possible to write the following. Playground
type ThenArgRecursive<T> = T extends PromiseLike<infer U> ? ThenArgRecursive<U> : T
type Str = ThenArgRecursive<Promise<Promise<Promise<string>>>> // string
对于禁止递归类型的旧版 TypeScript,您可以通过使用递归类型别名来解决此问题,但请注意,这些版本官方不支持(尽管实际上,通常很好).游乐场
For older versions of TypeScript, which ban recursive types, you can work around this issue by using a recursive type alias, but be aware that this is officially not supported in those versions (though practically, usually fine). Playground
type ThenArgRecursive<T> = T extends PromiseLike<infer U>
? { 0: ThenArgRecursive<U>; 1: U }[U extends PromiseLike<any> ? 0 : 1]
: T
type Str = ThenArgRecursive<Promise<Promise<Promise<string>>>> // string
这篇关于如何解开 Promise 的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!