Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Or is this some magical TypeScript syntax?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading