Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript array of functions

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 ?

like image 846
Eduard Dumitru Avatar asked Feb 02 '13 14:02

Eduard Dumitru


People also ask

How do you define a function array in TypeScript?

To specify the type of an array like [1, 2, 3] , you can use the syntax number[] ; this syntax works for any type (e.g. string[] is an array of strings, and so on).

Should I use [] or array in TypeScript?

There is no difference at all. Type[] is the shorthand syntax for an array of Type . Array<Type> is the generic syntax.

How do I return an array from a function in TypeScript?

To declare a function with an array return type, set the return type of the function to an array right after the function's parameter list, e.g. function getArr(): string[] {} . If the return type of the function is not set, TypeScript will infer it.

Can you have an array of functions JavaScript?

To execute an array of functions, we can use a for loop or the forEach() array method in JavaScript.


1 Answers

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[];
}
like image 55
Ryan Cavanaugh Avatar answered Oct 02 '22 20:10

Ryan Cavanaugh