如何在TypeScript中将函数类型转换为异步类型?

时间:2019-12-01 12:55:48

标签: typescript promise async-await

如何相对于其输入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);
}

TypeScript Playground link

有没有更好/更短的方法来实现这一目标?

1 个答案:

答案 0 :(得分:1)

您可以通过为函数参数和返回类型定义单独的类型参数AR来稍微缩短类型,以便自动推断它们。然后,很容易在Promisesample)中将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>