Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Typed array of functions

Tags:

typescript

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

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: (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.

Any ideas?

Answer: Thanks to mohamed below, here's an example that works in the 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(); 
like image 397
Matt Burland Avatar asked Oct 04 '12 19:10

Matt Burland


People also ask

What is a function array?

An array formula is a formula that can perform multiple calculations on one or more items in an array. You can think of an array as a row or column of values, or a combination of rows and columns of values. Array formulas can return either multiple results, or a single result.

How do you type an array?

To create an array type you can use Array<Type> type where Type is the type of elements in the array. For example, to create a type for an array of numbers you use Array<number> . You can put any type within Array<Type> .

What is type of array in JavaScript?

Arrays are just regular objects In Javascript, there are only 6 data types defined – the primitives (boolean, number, string, null, undefined) and object (the only reference type). Arrays do not belong to this list because they are objects as well.

What is array explain types of array?

An array type is a user-defined data type consisting of an ordered set of elements of a single data type. An ordinary array type has a defined upper bound on the number of elements and uses the ordinal position as the array index.


2 Answers

You can find this in the language spec section 3.6.4:

foo: { (data: string): void; } [] 
like image 178
mohamed hegazy Avatar answered Oct 08 '22 23:10

mohamed hegazy


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)[]; 
like image 30
Saravana Avatar answered Oct 09 '22 01:10

Saravana