Looking to create a function that requires the following inputs:
- an array
- a filter logic function (predicate function)
In JavaScript, you can use the following code successfully:
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, when attempting it in TypeScript, an error occurs:
const myFilter = (func: Function, arr: any[]): any[] => arr.filter(func)
// ^
// (parameter) func: Function
// No overload matches this call.
Even though using any
for func
resolves the error, questions still remain:
- Why doesn't typing
Function
work? - What would be the correct type for the
func
parameter?