2012-10-03 8 views
19

UPDATE - il contesto di questa domanda era pre-TypeScript 1.4. Da quella versione, la mia prima ipotesi è stata supportata dalla lingua. Vedi l'aggiornamento alla risposta.In TypeScript, come si dichiara un array di funzioni che accettano una stringa e restituiscono una stringa?


posso dichiarare f ad essere una funzione che accetta una stringa e restituisce una stringa:

var f : (string) => string 

E posso dichiarare g essere un array di stringhe:

var g : string[] 

Come posso dichiarare h come un array di "funzione che accetta una stringa e restituisce una stringa"?

La mia prima risposta:

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

Questo sembra essere un errore di sintassi. Se tolgo le parentesi aggiuntive, allora è una funzione da stringa ad array di stringhe.

risposta

38

L'ho capito. Il problema è che il => per un tipo di funzione letterale è esso stesso solo zucchero sintattico e non vuole comporre con [].

Mentre spec dice:

Un tipo letterale funzione della forma

(paramlist) => ReturnType

è esattamente equivalente al tipo di oggetto letterale

{(ParamList): ReturnType}

Quindi quello che voglio è:

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

Esempio completo:

var f : (string) => string 

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

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

h = []; 

h.push(f); 

Aggiornamento:

A giudicare da this changeset parentesi sarà consentito nelle dichiarazioni di tipo a 1.4, quindi la "prima ipotesi "nella domanda sarà anche corretto:

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

Ulteriore aggiornamento È in 1,4!

+3

+1 Buone capacità! – Fenton

0

Sulla base della sua ricerca ho scritto un po 'di classe 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(); 
Problemi correlati