TypeScript函数数组 [英] TypeScript array of functions

查看:66
本文介绍了TypeScript函数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆