29

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.

2 Answers 2

44

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!

Sign up to request clarification or add additional context in comments.

Comments

1

Based on your research I wrote a little class PlanetGreeter/SayHello:`

/* PlanetGreeter */

class PlanetGreeter {
    hello    : { () : void; } [] = [];
    planet_1 : string = "World";
    planet_2 : string = "Mars";
    planet_3 : string = "Venus";
    planet_4 : string = "Uranus";
    planet_5 : string = "Pluto";
    constructor() {
        this.hello.push( () => { this.greet(this.planet_1); } );
        this.hello.push( () => { this.greet(this.planet_2); } );
        this.hello.push( () => { this.greet(this.planet_3); } );
        this.hello.push( () => { this.greet(this.planet_4); } );
        this.hello.push( () => { this.greet(this.planet_5); } );
    } 
    greet(a: string): void { alert("Hello " + a); }
    greetRandomPlanet():void { 
        this.hello [ Math.floor( 5 * Math.random() ) ] (); 
    } 
} 
new PlanetGreeter().greetRandomPlanet();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.