peter flanagan
peter flanagan

Reputation: 9830

How to declare a function type in typescript

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

Answers (3)

Oram
Oram

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

AntonB
AntonB

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

siddharth shah
siddharth shah

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

Related Questions