I just found a line in a TypeScript file inside a class which looks like
private handlers: ((event: string) => void)[]
Then there is another function:
private fire(event: string): void {
for (const handler of this.handlers) {
handler(event);
}
}
So my guess would be that each array element has a function which can be called but I really don't understand how this is working. If every element has that function attached which returns always void, shouldn't be all array elements complete empty?
Or is this some magical TypeScript syntax?
CodePudding user response:
Brackets []
in typescript declares an array. And the syntax of (...params: any[]) => any
declares a function. So combined together (and using the parentheses!) you will get an array of functions.
This means that the handlers
property is an array of functions, which all take one parameter event
of type string
and return void
. So the elements inside the array don't all "have" a function, that can be called, but they are functions.
The important thing to note here, is that the array only holds the functions. They are not invoked. To actually run the functions you'd have to obtain them (through iteration or indexing the array) and invoke them, with the specified parameter(s), like you would every other function.
CodePudding user response:
Maybe it's easier to understand it you read it like this:
private handlers: Function[]