【问题标题】:In TypeScript how do I declare an array of functions that accept a string and return a string?在 TypeScript 中,如何声明一个接受字符串并返回字符串的函数数组?
【发布时间】:2012-09-24 05:50:29
【问题描述】:

更新 - 这个问题的上下文是 TypeScript 1.4 之前的版本。从那个版本开始,我的第一个猜测就得到了语言的支持。查看答案的更新。


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

var f : (string) => string

我可以将g 声明为一个字符串数组:

var g : string[]

如何将h 声明为“接受字符串并返回字符串的函数”的数组?

我的第一个猜测:

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

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

【问题讨论】:

    标签: arrays function typescript


    【解决方案1】:

    我想通了。问题是函数类型文字的=> 本身只是语法糖,不想与[] 组合。

    正如规范所说:

    形式为

    的函数类型字面量

    ( 参数列表 ) => 返回类型

    完全等同于对象类型字面量

    { ( 参数列表 ) : 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中的类型声明中将允许使用括号,因此问题中的“第一个猜测”也将是正确的:

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

    进一步更新在 1.4 中!

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2017-06-12
        • 2015-02-10
        • 2022-11-15
        • 1970-01-01
        • 1970-01-01
        • 2021-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多