Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a function type in typescript

Tags:

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)
}
like image 798
peter flanagan Avatar asked Nov 30 '25 01:11

peter flanagan


2 Answers

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)
}
like image 177
AntonB Avatar answered Dec 02 '25 05:12

AntonB


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.

like image 24
Oram Avatar answered Dec 02 '25 05:12

Oram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!