【发布时间】:2020-12-12 08:42:40
【问题描述】:
我有一个包装函数 (doesPromiseyThings),它接受一个 thunk 并在 Promise 中返回 thunk 的返回值。我想创建另一个包装器来处理 thunk 的创建 - 创建一个函数,该函数采用与原始参数相同的参数,返回原始的 Promise 包装类型,并在执行时通过 doesPromiseyThings 传递函数。
当我尝试这样做时,传入一个返回承诺的函数,我返回的类型都是 Promise<Promise<T>>,TypeScript 抱怨这与 Promise<T> 不一样我试图分配返回值到。
async function foo(param: number) {
return param;
}
function doesPromiseyThings<T>(fn: () => T): Promise<T> {
return Promise.resolve(fn());
}
function wrapper<T,U>(fn: (...args: T[]) => U) {
return (...args: T[]) => doesPromiseyThings(fn);
}
const wrappedFoo = wrapper(foo);
// (...args: number[]) => Promise<Promise<number>>
const output = wrappedFoo(1);
// Promise<Promise<number>>
我尝试在包装器的返回值中解包 Promise,但这样做会出现类型错误:
function wrapper<T,U>(fn: (...args: T[]) => U): (...args: T[]) => Promise<U extends Promise<infer V> ? V : U> {
return (...args: T[]) => doesPromiseyThings(fn);
}
/*
Type '(...args: T[]) => Promise<U>' is not assignable to type '(...args: T[]) => Promise<U extends Promise<infer V> ? V : U>'.
Type 'Promise<U>' is not assignable to type 'Promise<U extends Promise<infer V> ? V : U>'.
Type 'U' is not assignable to type 'U extends Promise<infer V> ? V : U'.(2322)
*/
【问题讨论】:
标签: typescript promise es6-promise