TypeScriptでは、文字列を受け入れて文字列を返す関数の配列を宣言するにはどうすればよいですか?
-
13-12-2019 - |
質問
更新 -この質問のコンテキストは、TypeScript1.4より前のものでした。そのバージョン以来、私の最初の推測は言語によってサポートされています。答えの更新を参照してください。
私は宣言することができます f
文字列を受け入れて文字列を返す関数にするには:
var f : (string) => string
そして、私は宣言することができます g
文字列の配列にするには:
var g : string[]
どうすれば宣言できますか h
「文字列を受け入れて文字列を返す関数」の配列にするには?
私の最初の推測:
var h : ((string) => string)[]
それは構文エラーのようです。余分な括弧を取り除くと、文字列から文字列の配列への関数になります。
解決
私はそれを理解しました。問題は、 =>
関数型リテラルの場合、それ自体は単なる構文上の砂糖であり、で構成したくありません []
.
仕様が言うように:
次の形式の関数型リテラル
(ParamList)=>ReturnType
オブジェクト型リテラルとまったく同じです
{(ParamList) :リターンタイプ}
だから私が欲しいのは:
var h : { (s: string): string; }[]
完全な例:
var f : (string) => string
f = x => '(' + x + ')';
var h : { (s: string): string; }[]
h = [];
h.push(f);
更新:
から判断すると このチェンジセット 括弧は1.4の型宣言で許可されるので、質問の「最初の推測」も正しいでしょう:
var h: ((string) => string)[]
更なる更新 それは1.4にあります!
他のヒント
あなたの研究に基づいて、私は少しクラス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();
所属していません StackOverflow