A Typed array of functions
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:
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?
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?
Answer: Thanks to mohamed below, here's an example that works in the TypeScript Playground:
class whatever {
public foo: { (data: string): void; }[] = [];
dofoo() {
for (var i=0; i < this.foo.length; i++) {
this.foo[i]("test");
}
}
}
var d = new whatever();
d.foo.push(function(bar){alert(bar)})
d.foo.push(function(bar){alert(bar.length.toString())})
d.dofoo();
You can find this in the language spec section 3.6.4:
foo: { (data: string): void; } []
Other (newer, more readable) ways to type an array of functions using fat arrows:
let foo: Array<(data: string) => void>;
let bar: ((data: string) => void)[];
or foo: ((data: string) => void)[]
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");