简体   繁体   中英

What does that line of TypeScript mean?

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?

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.

Maybe it's easier to understand it you read it like this:

private handlers: Function[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM