25

更新- この質問のコンテキストは、TypeScript 1.4 より前のものでした。そのバージョン以降、私の最初の推測は言語によってサポートされています。回答の更新を参照してください。


f文字列を受け取り、文字列を返す関数として宣言できます。

var f : (string) => string

gそして、文字列の配列であると宣言できます。

var g : string[]

h「文字列を受け取って文字列を返す関数」の配列であることを宣言するにはどうすればよいですか?

私の最初の推測:

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

構文エラーのようです。余分な括弧を取り除くと、文字列から文字列の配列への関数になります。

4

2 に答える 2

42

私はそれを考え出した。問題は=>、関数型リテラルのfor自体が単なる構文糖衣であり、で構成したくないということです[]

仕様が言うように:

次の形式の関数型リテラル

(ParamList)=> ReturnType

オブジェクト型リテラルとまったく同じです

{(ParamList):ReturnType}

だから私が欲しいのは:

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

完全な例:

var f : (string) => string

f = x => '(' + x + ')';

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

h = [];

h.push(f);

更新

このチェンジセットの括弧から判断すると、1.4の型宣言で許可されるため、質問の「最初の推測」も正しくなります。

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

さらなるアップデート1.4にあります!

于 2012-10-03T11:00:23.407 に答える
0

あなたの調査に基づいて、私は小さなクラス 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();
于 2014-03-31T09:19:54.260 に答える