20

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)
}
1

3 Answers 3

15

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

(address: string) => void is probably better. Since useSubscription doesn't use the return value from successHandler, it shouldn't require one.
6

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.

4 Comments

True, but this is not type checking. This is just making typescript be quiet. Since we call successHandler(address), we should declare a type that insures that will work, ie (address: string) => void.
Of course it is type checking. You can't pass anything that is not a function. In the original question there is no definition for the function. While it's reasonable to assume (address: string) => void, (address: string) => ANYTHING is also valid.
What I mean is the type checking's not doing it's job; it shuts typescript up without providing the protection typescript is meant to provide. We want to know we can pass address to successHandler. Function doesn't insure that. As for your second point, yes, (address: string) => void permits (address: string) => ANYTHING. The void keyword tells typescript it can ignore the return value.
But we do check the address type as well, you are just double specifying that address has to be a string
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.