2012-10-03 47 views
19

UPDATE - 此問題的上下文是TypeScript 1.4之前的版本。自從那個版本以來,我的第一個猜測已經得到了該語言的支持。查看答案的更新。在TypeScript中,我該如何聲明一個接受字符串並返回字符串的函數數組?


我可以聲明f是接受字符串並返回字符串的函數:

var f : (string) => string 

我可以聲明g是字符串的數組:

var g : string[] 

我如何聲明h是一個「接受字符串並返回字符串的函數」的數組?

我的第一個猜想:

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

這似乎是一個語法錯誤。如果我拿走多餘的括號,那麼它是一個從字符串到字符串數組的函數。

回答

38

我想通了。問題是函數類型literal的=>本身僅僅是語法糖,不想和[]合成。

作爲規範說:

函數類型字面的形式

(ParamList)=>返回類型

的是完全等同於該對象類型字面

{( ParamList):ReturnType}

所以,我要的是:

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

完整的示例:

var f : (string) => string 

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

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

h = []; 

h.push(f); 

更新

this changeset括號評選工作將在類型聲明被允許在1.4,所以「第一個猜測「在問題中也將是正確的:

​​

更多更新它在1.4!

+3

+1良好的技能! – Fenton

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(); 
相關問題