我想设计一个包装任何异步功能的库。包装的异步函数可以有多个参数
如果我愿意
type AsyncFunction<I, O> = (inputs: I) => Promise<O>;
function wrapper<I, O>(
asyncFunction: AsyncFunction<I, O>,
): AsyncFunction<I, O> { ... }
T的类型仅适用于第一个arg,因此这使我的包装器无法用于带有多个参数的任何异步函数。
有人可以给我一个支持多个参数的解决方案吗?
修改
这是我目前所在的位置:
type AsyncFunction<I extends any[], O> = (...inputs: I) => Promise<O>;
export function onlyResolvesLast<I extends any[], O>(
asyncFunction: AsyncFunction<I, O>,
): AsyncFunction<I, O> {
let cancelPrevious;
return function wrappedAsyncFunction(...args) {
cancelPrevious && cancelPrevious();
const initialPromise = asyncFunction(...args);
const { promise, cancel } = createImperativePromise(initialPromise);
cancelPrevious = cancel;
return promise;
};
}
答案 0 :(得分:2)
如果要支持多个参数,则需要使用tuples in rest parameters:
type AsyncFunction<I extends any[], O> = (...inputs: I) => Promise<O>;
function wrapper<I extends any[], O>(
asyncFunction: AsyncFunction<I, O>,
): AsyncFunction<I, O> { return asyncFunction }
async function fn(a: number, b: number) {
return 1;
}
wrapper(fn)(1, 2)
答案 1 :(得分:0)
我在现有的typedef中找到了所需的解决方案:
// Type definitions for debounce-promise 3.1
// Project: https://github.com/bjoerge/debounce-promise
// Definitions by: Wu Haotian <https://github.com/whtsky>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0
declare namespace debounce {
interface DebounceOptions {
leading?: boolean;
accumulate?: boolean;
}
}
type ArgumentsType<T> = T extends (...args: infer A) => any ? A : never;
declare function debounce<T extends (...args: any[]) => any>(
func: T,
wait?: number,
options?: debounce.DebounceOptions
): (
...args: ArgumentsType<T>
) => ReturnType<T> extends Promise<any>
? ReturnType<T>
: Promise<ReturnType<T>>;
export = debounce;