Typescript 泛型:将函数及其参数传递给包装函数

huangapple go评论70阅读模式
英文:

Typescript generics: pass a function and its parameters to a wrapper function

问题

我试图找出一种类型安全的方法来将函数和它的参数(无论参数数量是多少)传递给 TypeScript 中的另一个包装函数。我想要实现的是以下内容:

const myFunc1 = () => {...};
wrapper(myFunc1);

const myFunc2 = (a: string) => {...};
wrapper(myFunc2, 'hello');

const myFunc3 = (a: string, b: number) => {...};
wrapper(myFunc3, 'hello', 10);

这是我的尝试:

function wrapper<A extends (...params: B[]) => any, B extends any>(x: A, ...y: B[]) {}
英文:

I am trying to figure out a type safe way to pass the function and its parameters (whatever is the number of parameters) to another wrapper function in typescript. What I want to achieve is following:

const myFunc1 = () =&gt; {...};
wrapper(myFunc1);

const myFunc2 = (a: string) =&gt; {...};
wrapper(myFunc2, &#39;hello&#39;);

const myFunc3 = (a: string, b: number) =&gt; {...};
wrapper(myFunc3, &#39;hello&#39;, 10);

Here is my attempt:

function wrapper&lt;A extends (...params: B[]) =&gt; any, B extends any&gt;(x: A, ...y: B[]) {}

答案1

得分: 1

使用 Parameters 实用程序在 y 上:

function wrapper&lt;A extends (...params: any[]) =&gt; any&gt;(x: A, ...y: Parameters&lt;A&gt;) {

您还可以使用 ReturnType 实用程序注释返回类型,将其作为 A 的返回类型:

function wrapper&lt;A extends (...params: any[]) =&gt; any&gt;(x: A, ...y: Parameters&lt;A&gt;): ReturnType&lt;A&gt; {
    return x.call(undefined, ...y);
}

Playground

英文:

Use the Parameters utility on y:

function wrapper&lt;A extends (...params: any[]) =&gt; any&gt;(x: A, ...y: Parameters&lt;A&gt;) {

You can also annotate the return type as the return type of A using the ReturnType utility:

function wrapper&lt;A extends (...params: any[]) =&gt; any&gt;(x: A, ...y: Parameters&lt;A&gt;): ReturnType&lt;A&gt; {
    return x.call(undefined, ...y);
}

Playground

huangapple
  • 本文由 发表于 2023年4月6日 21:50:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定