简体   繁体   English

TypeScript 这一行是什么意思?

[英]What does that line of TypeScript mean?

I just found a line in a TypeScript file inside a class which looks like我刚刚在 class 中的 TypeScript 文件中找到一行,看起来像

private handlers: ((event: string) => void)[]

Then there is another function:然后还有一个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.所以我的猜测是每个数组元素都有一个可以调用的 function 但我真的不明白这是如何工作的。 If every element has that function attached which returns always void, shouldn't be all array elements complete empty?如果每个元素都附加了 function,它总是返回 void,那么所有数组元素不应该都是空的吗?

Or is this some magical TypeScript syntax?或者这是一些神奇的 TypeScript 语法?

Brackets [] in typescript declares an array. typescript中的括号[]声明了一个数组。 And the syntax of (...params: any[]) => any declares a function. So combined together (and using the parentheses.) you will get an array of functions. (...params: any[]) => any的语法声明了一个 function。因此组合在一起(并使用括号。)你将得到一个函数数组。

This means that the handlers property is an array of functions, which all take one parameter event of type string and return void .这意味着handlers属性是一组函数,它们都接受一个string类型的参数event并返回void So the elements inside the array don't all " have " a function, that can be called, but they are functions.所以数组里面的元素并不是都“”一个function,可以调用,但是它们函数。

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.要实际运行这些函数,您必须获取它们(通过迭代或索引数组)并使用指定的参数调用它们,就像您调用其他 function 一样。

Maybe it's easier to understand it you read it like this:你这样读可能更容易理解:

private handlers: Function[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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