试图将一个函数包装在另一个函数中的打字稿错误 [英] Typescript error trying to wrap a function inside another function

查看:58
本文介绍了试图将一个函数包装在另一个函数中的打字稿错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个函数包装在另一个函数中,然后再将其传递给稍后运行的库.我在尝试使用 .apply() 和传播参数时遇到各种 Typescript 错误.

I'm trying to wrap a function inside another function before passing it to a library to be run later. I'm getting all sorts of Typescript errors trying to use .apply() and spreading arguments.

图书馆要求我传递一个选项"对象包括一个名为 PromiseFn 的函数,该函数将由库使用任意数量的参数调用.

The library requires me to pass an "options" object including a function called PromiseFn to it which will be called by the library with an arbitrary number of arguments.

我需要将 promiseFn 包装在一个新函数中,该函数将在调用原始 promiseFn 之前和之后运行一些代码.新函数将是传递给库的函数.这是我试过的.

I need to wrap the promiseFn in a new function which will run some code before and after calling the original promiseFn. The new function will be the one passed to the library. This is what I've tried.

let newOptions = options

if(options.promiseFn !== undefined){

    let newPromiseFn = async (...args: any[]) => {

        ... before code

        await options.promiseFn?.apply(this, ...args)

        ... before code

    }

    newOptions.promiseFn = newPromiseFn

}

const { data } = useAsync(newOptions)

我目前遇到的打字稿错误是...

The typescript error that I'm currently getting is...

(参数) args: any[]预期 1-2 个参数,但得到 1 个或更多.ts(2556)

它与这一行中的参数有关

It relates to the args in this line

await options.promiseFn?.apply(this, ...args)

任何帮助将不胜感激.

推荐答案

如果我很理解你的问题,你只是想使用可以包装你的函数的东西.

If I understand well your problem, you just want to use something that can wrap your function.

我认为你可以使用这样的东西:

I think you can use something like this :

type GetReturnType<original extends Function> = original extends (...x: any[]) => infer returnType ? returnType : never;
type GetArgumentsType<originalArguments> = originalArguments extends (...args: infer formatArguments) => any ? formatArguments : never[];

const myEncapsulatedFunction = async <T extends Function>(
    func: T,
    ...args: GetArgumentsType<T>
): Promise<GetReturnType<T>> => wrappingFunction(func, args)();

然后你可以像这样使用这个包装器:

Then you can just use this wrapper like that:

function wrappingFunction<T extends any[]>(func: Function, args: T) {
  // Do some stuff here
  await func(...args)
  // Do some stuff here
}

// Then
function doStuff(arg: string) {
  console.log(arg)
}


myEncapsulatedFunction(doStuff, 'hello');

这篇关于试图将一个函数包装在另一个函数中的打字稿错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆