TypeScript array of functions

廉价感情. 提交于 2021-01-27 04:08:26

问题


I was wondering how could one declare a typed-function array in TypeScript.

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

causes a compiler error.

Does anyone have an idea of how this could be accomplished ?


回答1:


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


来源:https://stackoverflow.com/questions/14662995/typescript-array-of-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!