[英]Function that takes generic arguments and returns generic value
I have a function: 我有一个功能:
const r = (array, function) => { some stuff }
However array
and function
arguments can be anything , but array must be typeof array and function must be typeof function . 但是
array
和function
参数可以是任何东西 ,但是array 必须是typeof array,而function 必须是typeof function 。
However, the array
can be array of anything - any[]
anf function
can be anything function(...r: any): any
. 但是,该
array
可以是任何东西的数组-any any[]
anf function
可以是任何东西function(...r: any): any
。
How can I type that r
function to accept generic array
and function
arguments, but the type definition has to be passed when calling it? 如何键入该
r
函数以接受通用array
和function
参数,但是在调用它时必须传递类型定义?
Eg Im calling it somewhere in my app: 例如,我在应用程序的某处调用它:
r([1,2,3], (r) => r + 2)
Thanks! 谢谢!
This is my interpretation of what your're looking for 这是我对您要寻找的内容的解释
type Fn<T> = (arg: T) => T
type R = <T>(array: T[], fn: Fn<T>) => T
const r: R = (array, fn) => {
//some stuff
}
I prefer to split the type declaration and its usage. 我更喜欢拆分类型声明及其用法。
尝试这个:
const r = <T>(array: T[], fn: (argument: T) => T) => { /* ... */}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.