You can shorten up the types a bit by defining separate type parameters A
, R
for the function parameters and return type, so they are inferred automatically.
(您可以通过为函数参数和返回类型定义单独的类型参数A
, R
来稍微缩短类型,以便自动推断它们。)
Then it is easy to just wrap a Promise
around R
in makeAsync2
( sample ): (然后,很容易将Promise
包裹在makeAsync2
( 样本 )中的R
周围:)
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>
Edit:
(编辑:)
If the input function potentially can itself return a promise, we can flatten the return type of makeAsync2
, so promises don't get nested ( sample ):
(如果输入函数本身可能会返回一个promise,我们可以将makeAsync2
的返回类型展平,因此promise不会被嵌套( sample ):)
// this works for a single nested promise
type FlattenPromise<T> = T extends Promise<any> ? T : Promise<T>
declare function makeAsync2<A extends any[], R>(fn: (...args: A) => R): (...args: A) => FlattenPromise<R>
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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…