typescript 类型化的函数数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12734660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:49:25  来源:igfitidea点击:

A Typed array of functions

typescript

提问by Matt Burland

I'm struggling to figure out if it's possible in TypeScript to declare a statically typed array of functions.

我正在努力弄清楚是否可以在 TypeScript 中声明一个静态类型的函数数组。

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 成为一个接受字符串并且不返回任何内容的函数数组,我该怎么做?

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.

不起作用,因为 TypeScript 认为它是一个函数,它接受一个字符串并返回一个 void 数组,而且它似乎不喜欢我试图将函数包装在括号中。

Any ideas?

有任何想法吗?

Answer: Thanks to mohamed below, here's an example that works in the TypeScript Playground:

:感谢下面的 mohamed,这是一个在 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();

回答by mohamed hegazy

You can find this in the language specsection 3.5.5:

您可以在语言规范第 3.5.5 节中找到它:

foo: { (data: string): void; } []

回答by Saravana

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)[];

回答by aaron

or foo: ((data: string) => void)[]

或者 foo: ((data: string) => void)[]

回答by Janderson Silva

If you wish declare an array of callable function in TypeScript, you can declare a type:

如果你想在 TypeScript 中声明一个可调用函数数组,你可以声明一个类型:

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");