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 );
});
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With