TypeScript函数数组 [英] TypeScript array of functions
问题描述
我想知道如何在TypeScript中声明类型函数数组.
I was wondering how could one declare a typed-function array in TypeScript.
例如,假设我有一个字段可以容纳一个没有参数的函数并返回void:
For instance, say I have a field which can hold a function that has no arguments and returns void:
private func: () => void;
现在,说我想要一个可以容纳此类函数数组的字段:
Now, say I wanted a field which can hold an array of such functions:
private funcs: () => void [];
这显然是错误的方法,因为编译器认为这是一个返回空数组的函数.
This is obviously the wrong way to do what I intended since the compiler considers this to be a function which returns an array of voids.
尝试用括号分隔内联原型声明,如下所示:
Trying to isolate the inline prototype declaration with parentheses as in:
private funcs2: ( () => void ) [];
导致编译器错误.
有人知道如何实现吗?
推荐答案
您需要使用完整类型的文字语法,而不是 =>
的简写:
You'll need to use the full type literal syntax instead of the =>
shorthand:
private funcs: { (): void; }[];
如果界面看起来太怪异,您还可以创建一个界面:
You could also make an interface if that looks too weird:
// (elsewhere at top-level)
interface foo {
(): void;
}
class etc {
private funcs: foo[];
}
这篇关于TypeScript函数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!