是否可以包装函数并保留其类型? [英] Is it possible to wrap a function and retain its types?

查看:28
本文介绍了是否可以包装函数并保留其类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通用包装函数,它将包装传递给它的任何函数.

I'm trying to create a generic wrapper function which will wrap any function passed to it.

在最基本的包装函数看起来像

At the very basic the wrapper function would look something like

function wrap<T extends Function>(fn: T) {
    return (...args) => {
        return fn(...args)
    };
}

我正在尝试使用它:

function foo(a: string, b: number): [string, number] {
    return [a, b];
}

const wrappedFoo = wrap(foo);

现在 wrappedFoo 正在获取一种 (...args: any[]) =>任何

Right now wrappedFoo is getting a type of (...args: any[]) => any

是否可以让 wrappedFoo 模仿其包装的函数类型?

Is it possible to get wrappedFoo to mimic the types of the function its wrapping?

推荐答案

这适用于任意数量的参数,并保留所有参数 &返回类型

This works with any number of arguments, and keep all the arguments & return types

const wrap = <T extends Array<any>, U>(fn: (...args: T) => U) => {
  return (...args: T): U => fn(...args)
}

这篇关于是否可以包装函数并保留其类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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