Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript error on callback function: Type 'Function' provides no match for the signature

Tags:

typescript

I'm an error that Type 'Function' provides no match for the signature for the filter below. Which is true because filter expects a specific type. How would define my callback to match what filter expects?

private _getItemFilteredBy(itemName: string, Fn: Function): Observable<any[]> {
    return this.getItemByName(itemName)
        .map((items: any[]) => {
            return items.filter( Fn );
        });
}
like image 630
dan Avatar asked Sep 02 '16 11:09

dan


People also ask

How do you define a type of callback function in TypeScript?

Use Type Keyword to Declare Callback Type in TypeScript So with the help of the type keyword, you could declare your callback type as shown below. Copy type callBackFunction = () => void; This declares a function that does not take any arguments and returns nothing.

How do you pass a callback function in TypeScript?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.

What is the type for function in TypeScript?

Introduction to TypeScript function types The function type accepts two arguments: x and y with the type number . The type of the return value is number that follows the fat arrow ( => ) appeared between parameters and return type.

Is not assignable to parameter of type function?

The error message "Argument of type 'void' is not assignable to parameter of type" means that we are passing an argument of type void to a function that expects a parameter of a different type. To solve the error, make sure to return a value from your functions.


1 Answers

Filter needs a predicate. Change the type to (x:any) => boolean

private _getItemFilteredBy(itemName: string, Fn: (x:any) => boolean): Observable<any[]> {
    return this.getItemByName(itemName)
        .map((items: any[]) => {
            return items.filter( Fn );
        });
}

If you have more specific type information than 'any', I'd recommend updating that too but what I've posted above should work.

like image 178
Paarth Avatar answered Sep 19 '22 16:09

Paarth