Issue
I want to type a function that takes as inputs:
- array
- a function for filtering logic (predicate function)
In JavaScript, the following works as expected:
const myFilter = (func, arr) => arr.filter(func)
const myArr = [1, 2, 3, 4, 5, 6]
const res = myFilter(x => x > 3, myArr)
console.log(res) // => [ 4, 5, 6 ]
However, in TypeScript it throws an error:
const myFilter = (func: Function, arr: any[]): any[] => arr.filter(func)
// ^
// (parameter) func: Function
// No overload matches this call.
Although typing func
as any
solves the error, I still want to know:
- how come that type
Function
doesn't work? - what would be a proper type for
func
parameter?
Solution
With generic you can write, look at the second parameter func
defined like a callback. Array<T>
- this is referred as generic type, where T is the generic type supplied while calling the function, whatever you supply would become T. Sp it could be number or string or integer like that, if you pass number which your example is sending T would te number.
const myFilter = <T,>(arr: Array<T>, func: (value: T) => any) => {
return arr.filter(func);
}
const myArr = [1, 2, 3, 4, 5, 6];
const res = myFilter(myArr, x => x > 3);
console.log(res);
You can even constraint the type like this. So now you will have to always pass array of numbers but not anything else.
const myFilter = <T extends number>(arr: Array<T>, func: (value: T) => any) => {
return arr.filter(func)
}
With your specific question without using generic it can be simply written like this,
const myFilter = (arr: Array<any>, func: (value: number) => any) => {
return arr.filter(func)
}
const myArr = [1, 2, 3, 4, 5, 6]
const res = myFilter(myArr, x => x > 3)
console.log(res);
Answered By - Navoneel Talukdar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.