8

How would you declare an array of callbacks in TypeScript?

A single callback looks like this:

var callback:(param:string)=>void = function(param:string) {};

So an array of callbacks should look like this:

var callback:(param:string)=>void[] = [];

However, that creates ambiguity, since I could mean an array of callbacks, or a single callback which returns an array of voids.

In the TypeScript playground, it thinks it is an array of voids. So, my next though was to wrap it in parentheses:

var callback:((param:string)=>void)[] = [];

But that doesn't work either.

Any other ideas?

1 Answer 1

18

You'll need to use the full type literal syntax form, like so:

var callback:{(param:string): void;}[] = [];

This is sort of ugly; if you like you can make a name for it first:

interface fn {
    (param: string): void;
}
var callback2: fn[] = [];
Sign up to request clarification or add additional context in comments.

2 Comments

Cool. That's much better than the any[] I temporarily had in there. Thanks. =)
Typescript gets so weird... sometimes you just want to store an array of callback listeners and you end up with this gibberish in your codebase.

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.