111

I'm struggling to figure out if it's possible in TypeScript to declare a statically typed array of functions.

For example, I can do this:

const foo: (data: string) => void = function (data) {};

But if I want foo to be an array of functions that take a string and return nothing, how do I do that?

const foo: (data: string) => void [] = [];

Doesn't work because TypeScript thinks it's a function that takes a string and returns an array of void, and it doesn't seem to like me trying to wrap the function in brackets.

Any ideas?

Updated answer from 2025:

const foo: ((data: string) => void)[] = [];

function doFoo() {
  for (var i = 0; i < this.foo.length; i++) {
     this.foo[i]("test");
  }
}

foo.push((bar) => { alert(bar) });
foo.push((bar) => { alert(bar.length.toString()) });

doFoo();
1

5 Answers 5

144

You can find this in the language spec section 3.6.4:

foo: { (data: string): void; } []
Sign up to request clarification or add additional context in comments.

10 Comments

Yep, that seemed to do it. Thanks.
@asawyer It has to be inside of a class or interface, and it has to have a semicolon at the end.
It can be a variable too: var foo: { (data: string): void; } [];
link to language spec is broken
Broken link: The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
|
94

Since this question was originally posted, there are now newer and more readable ways to type an array of functions:

const foo: ((data: string) => void)[];
const bar: Array<(data: string) => void>;

1 Comment

The first option here was the only syntax I could get to work with AssemblyScript.
17

Or const foo: ((data: string) => void)[]

Comments

9

If you wish declare an array of callable function in TypeScript, you can declare a type:

type Bar = (
  (data: string) => void
);

And then use it:

const foo: Bar[] = [];

const fooFn = (data: string) => console.log(data);
foo.push(fooFn);
foo.forEach((fooFn: Bar) => fooFn("Something");

Comments

1
type fn = (...args: any[]) => void

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.