英文:
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 = () => {...};
wrapper(myFunc1);
const myFunc2 = (a: string) => {...};
wrapper(myFunc2, 'hello');
const myFunc3 = (a: string, b: number) => {...};
wrapper(myFunc3, 'hello', 10);
Here is my attempt:
function wrapper<A extends (...params: B[]) => any, B extends any>(x: A, ...y: B[]) {}
答案1
得分: 1
使用 Parameters
实用程序在 y
上:
function wrapper<A extends (...params: any[]) => any>(x: A, ...y: Parameters<A>) {
您还可以使用 ReturnType
实用程序注释返回类型,将其作为 A
的返回类型:
function wrapper<A extends (...params: any[]) => any>(x: A, ...y: Parameters<A>): ReturnType<A> {
return x.call(undefined, ...y);
}
英文:
Use the Parameters
utility on y
:
function wrapper<A extends (...params: any[]) => any>(x: A, ...y: Parameters<A>) {
You can also annotate the return type as the return type of A
using the ReturnType
utility:
function wrapper<A extends (...params: any[]) => any>(x: A, ...y: Parameters<A>): ReturnType<A> {
return x.call(undefined, ...y);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论