Nel dattiloscritto Come posso dichiarare una serie di funzioni che accettano una stringa e restituiscono una stringa?
-
13-12-2019 - |
Domanda
Aggiornamento - Il contesto di questa domanda è stato pre-dattiloscritto 1.4.Dalla versione, la mia prima ipotesi è stata supportata dalla lingua.Vedi l'aggiornamento alla risposta.
.
Posso dichiarare f
per essere una funzione che accetta una stringa e restituisce una stringa:
var f : (string) => string
.
E posso dichiarare g
per essere una serie di stringa:
var g : string[]
.
Come posso dichiarare h
per essere una serie di "funzione che accetta una stringa e restituisce una stringa"?
La mia prima ipotesi:
var h : ((string) => string)[]
.
che sembra essere un errore di sintassi.Se prendo via le parentesi extra, allora è una funzione da una stringa a array di stringa.
Soluzione
L'ho capito.Il problema è che il =>
per un tipo di funzione Letterale è se stesso solo zucchero sintattico e non vuole comporre con []
.
Come dice la specifica:
.Un tipo di funzione Letterale del modulo
(Paramlist)=> Rotturhtype
è esattamente equivalente all'oggetto tipo letterale
{(Paramlist): ritorno}
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 Questo apmet Parentesi sarà consentito in Dichiarazioni di tipo in 1.4, quindi la "prima ipotesi" inLa domanda sarà anche corretta:
var h: ((string) => string)[]
.
Ulteriore aggiornamento È in 1.4!
Altri suggerimenti
Sulla base della tua ricerca ho scritto un PLANETTRETER PLANETTORE / 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();
.