Dans TypeScript, comment déclarer un tableau de fonctions qui acceptent une chaîne et renvoient une chaîne ?

StackOverflow https://stackoverflow.com//questions/12706161

  •  13-12-2019
  •  | 
  •  

Question

MISE À JOUR - le contexte de cette question était pré-TypeScript 1.4.Depuis cette version, ma première hypothèse a été prise en charge par le langage.Voir la mise à jour de la réponse.


je peux déclarer f être une fonction qui accepte une chaîne et renvoie une chaîne :

var f : (string) => string

Et je peux déclarer g être un tableau de chaînes :

var g : string[]

Comment puis-je déclarer h être un tableau de « fonction qui accepte une chaîne et renvoie une chaîne » ?

Ma première hypothèse :

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

Cela semble être une erreur de syntaxe.Si j'enlève les parenthèses supplémentaires, c'est une fonction de chaîne en tableau de chaîne.

Était-ce utile?

La solution

Je l'ai compris.Le problème est que le => car un littéral de type fonction est lui-même simplement du sucre syntaxique et ne veut pas composer avec [].

Comme le dit la spécification :

Un littéral de type fonction de la forme

( ParamList ) => Type de retour

est exactement équivalent au littéral du type d'objet

{ ( ListeParam ) :Type de retour }

Donc ce que je veux c'est :

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

Exemple complet :

var f : (string) => string

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

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

h = [];

h.push(f);

Mise à jour:

A en juger par cet ensemble de modifications les parenthèses seront autorisées dans les déclarations de type dans la version 1.4, donc la « première hypothèse » dans la question sera également correcte :

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

Mise à jour supplémentaire C'est en 1.4 !

Autres conseils

Sur la base de vos recherches, j'ai écrit un petit cours 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();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top