简体   繁体   English

定义一个通用的 function 类型来支持 TypeScript 中任意数量的任意类型的参数

[英]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.

相关问题 TypeScript - 如何输入一个 function 可以接受任意数量的字符串或数字参数? - TypeScript - how to type a function that can take any number of args that are either strings or numbers? TypeScript-如何使用任何类型的参数定义函数类型 - TypeScript - How to define Function Type having arguments with any Type 如何在TypeScript中定义具有任意数量的某种类型的属性的接口 - How to define an interface that has any number of properties of a certain type in TypeScript 为任何 Function React Typescript 定义 prop 的类型 - Define prop's type for any Function React Typescript 是否可以在 TypeScript 中使用一个没有“任何”的参数来定义代表 function 的类型? - Is it possible to define a type representing a function with one parameter without 'any' in TypeScript? TypeScript: Type &#39;T&#39; 不满足约束 &#39;(...args: any) =&gt; any&#39; - TypeScript: Type 'T' does not satisfy the constraint '(…args: any) => any' 如何在 TypeScript 中定义通用匿名 function 类型? - How to define a generic anonymous function type in TypeScript? 定义特定类型的通用打字稿排序功能 - Define generic typescript sort function of a certain type 无法为通用比较 function 与 typescript 定义类型 - Unable to define type for generic compare function with typescript 如何在打字稿中定义“任何字符串枚举”类型? - How to define the type "any string enum" in typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM