在TypeScript中,我该如何声明一个接受字符串并返回字符串的函数数组?

问题描述:

UPDATE - 此问题的上下文是TypeScript 1.4之前的版本。自从那个版本以来,我的第一个猜测已经得到了该语言的支持。查看答案的更新。在TypeScript中,我该如何声明一个接受字符串并返回字符串的函数数组?


我可以声明f是接受字符串并返回字符串的函数:

var f : (string) => string 

我可以声明g是字符串的数组:

var g : string[] 

我如何声明h是一个“接受字符串并返回字符串的函数”的数组?

我的第一个猜想:

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

这似乎是一个语法错误。如果我拿走多余的括号,那么它是一个从字符串到字符串数组的函数。

我想通了。问题是函数类型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

根据你的研究上我写了一个小类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();