如何相对于其输入fn
键入此函数?
function makeAsync(fn) {
return async (...args) => fn(...args);
}
它返回与输入相同的函数,但不是返回Type
,而是返回Promise<Type>
用法示例:
const a = () => 1; // Type () => number;
const b = makeAsync(a); // Type () => Promise<number>;
const c = makeAsync(b); // Type () => Promise<number>; // ✅, not Promise<Promise<number>>
这有效,但是有点冗长
// Unwraps a Promise<T> value into just T, so we never get Promise<Promise<T>>
type Unpromise<MaybePromise> = MaybePromise extends Promise<infer Type> ? Type : MaybePromise;
// Like ReturnType, except it returns the unwrapped promise also for async functions
type AsyncReturnType<T extends (...args: any[]) => any> = Unpromise<ReturnType<T>>
// For a `() => T` function it returns its async equivalent `() => Promise<T>`
type PromisedFunction<T extends (...args: any[]) => any> =
(...args: Parameters<T>) => Promise<AsyncReturnType<T>>;
function makeAsync<T extends (...args: any[]) => any>(fn: T): PromisedFunction<T> {
return async (...args) => fn(...args);
}
有没有更好/更短的方法来实现这一目标?
答案 0 :(得分:1)
您可以通过为函数参数和返回类型定义单独的类型参数A
,R
来稍微缩短类型,以便自动推断它们。然后,很容易在Promise
(sample)中将R
包裹在makeAsync2
周围:
declare function makeAsync2<A extends any[], R>(fn: (...args: A) => R): (...args: A) => Promise<R>
const c = (arg1: number, arg2: string[]) => 1; // (arg1: number, arg2: string) => number
const d = makeAsync2(c); // (arg1: number, arg2: string[]) => Promise<number>
const cResult = c(3, ["s"]) // number
const dResult = d(3, ["s"]) // Promise<number>
编辑:
如果输入函数fn
本身可以返回承诺,我们可以将其返回类型设置为联合R | Promise<R>
(sample):
function makeAsync2<A extends any[], R>(fn: (...args: A) => R | Promise<R>): (...args: A) => Promise<R> {
return async (...args) => fn(...args);
}
const e = (arg1: string) => Promise.resolve(3) // (arg1: string) => Promise<number>
const f = makeAsync2(e); // (arg1: string) => Promise<number>
const eResult = e("foo") // Promise<number>
const fResult = f("foo") // Promise<number>