Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In TypeScript how do I declare an array of functions that accept a string and return a string?

Tags:

UPDATE - the context of this question was pre-TypeScript 1.4. Since that version, my first guess has been supported by the language. See the update to the answer.


I can declare f to be a function that accepts a string and returns a string:

var f : (string) => string 

And I can declare g to be an array of string:

var g : string[] 

How can I declare h to be an array of "function that accepts a string and returns a string"?

My first guess:

var h : ((string) => string)[] 

That seems to be a syntax error. If I take away the extra parentheses then it's a function from string to array of string.

like image 567
Daniel Earwicker Avatar asked Oct 03 '12 10:10

Daniel Earwicker


People also ask

How do I return a string array 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. Copied!

How do you define a string array in TypeScript?

An array in TypeScript can contain elements of different data types using a generic array type syntax, as shown below. let values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana']; // or let values: Array<string | number> = ['Apple', 2, 'Orange', 3, 4, 'Banana'];

How do you declare an array of any type in TypeScript?

In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.

How do I return a string from a function in TypeScript?

The function's return type is string. Line function returns a string value to the caller. This is achieved by the return statement. The function greet() returns a string, which is stored in the variable msg.


1 Answers

I figured it out. The problem is that the => for a function type literal is itself merely syntactic sugar and doesn't want to compose with [].

As the spec says:

A function type literal of the form

( ParamList ) => ReturnType

is exactly equivalent to the object type literal

{ ( ParamList ) : ReturnType }

So what I want is:

var h : { (s: string): string; }[] 

Complete example:

var f : (string) => string  f = x => '(' + x + ')';  var h : { (s: string): string; }[]  h = [];  h.push(f); 

Update:

Judging from this changeset parentheses will be allowed in type declarations in 1.4, so the "first guess" in the question will also be correct:

var h: ((string) => string)[] 

Further Update It is in 1.4!

like image 181
Daniel Earwicker Avatar answered Oct 06 '22 07:10

Daniel Earwicker