[英]Define a generic function type to support any number of args with any type in TypeScript
In typescript we can define a function type like:在 typescript 中,我们可以定义一个 function 类型,例如:
type FunctionHandler = {
(param1: string, param2: number): string
}
But I want to declare a generic type that can take any number of params with their type as we do in variable typings like following:但是我想声明一个泛型类型,它可以像我们在变量类型中所做的那样接受任意数量的参数及其类型,如下所示:
type Variable<Props> = {
[p in keyof Props]: Props[p]
}
I want something like:我想要这样的东西:
type FunctionHandler<Props> = {
([p in keyof Props]: Props[p]): void | boolean
}
But I am not able to do it, can anyone help me with that?但是我做不到,有人可以帮我吗?
You can use a rest param like so to have the function accept any number of arguments of any type:您可以像这样使用 rest 参数让 function 接受任意数量的任何类型的 arguments:
type FunctionHandler = {
(...params: any): string
}
See also也可以看看
Try this:试试这个:
type FunctionHandler<TArgs extends any[]> = (...params: TArgs) => void;
Or, an even more generic type, including the return type:或者,一个更通用的类型,包括返回类型:
type FunctionHandler<TArgs extends any[], TReturn extends any> = (...params: TArgs) => TReturn;
Usage:用法:
function doSomthingWithHandler(handler: FunctionHandler){
const result = handler(123); // result will be of type `string`
}
doSomthingWithHandler((arg: number) => 'some string');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.