Reputation: 9830
I am working with typescript and passing a function into another function.
If I have a function that is passed into another function in typescript how should I write the type?
I have tried successHandler: function
but this doesn't appear to work.
export function useSubscription(address: string, successHandler: function) {
successHandler(address)
}
Upvotes: 19
Views: 35865
Reputation: 1673
You can declare it like this:
export function useSubscription(address: string, successHandler: (string) => void)) {
successHandler(address)
}
The change is with the capital F for Function
.
Upvotes: 5
Reputation: 2863
Declare a type with a function signature and pass it around as the type:
type SuccessHandler = (address: string) => string;
function useSubscription(address: string, successHandler: SuccessHandler) {
successHandler(address)
}
Upvotes: 14
Reputation: 1147
Her you can use callback function as a strongly typed parameter like this
class Menu {
addItem(callback: (n: string) => any) : void {
callback('Egg Roles');
}
}
var menu = new Menu();
var itemCallBack = (result: string) : void => {
alert(result);
}
menu.addItem(itemCallBack);
Here is the working example. Let me know if u have any doubt.
Upvotes: 0