首页 文章

在TypeScript中,如何声明接受字符串并返回字符串的函数数组?

提问于
浏览
22

UPDATE - 此问题的上下文是预先TypeScript 1.4 . 从那个版本开始,我的第一个猜测得到了语言的支持 . 请参阅答案的更新 .


我可以声明 f 是一个接受字符串并返回一个字符串的函数:

var f : (string) => string

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

var g : string[]

如何声明 h 是"function that accepts a string and returns a string"的数组?

我的第一个猜测:

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

这似乎是一个语法错误 . 如果我拿掉额外的括号,那么它是一个从字符串到字符串数组的函数 .

2 回答

  • 40

    我想到了 . 问题是函数类型文字的 => 本身只是语法糖,不想用 [] 组成 .

    正如规范所说:

    表单的函数类型文字(ParamList)=> ReturnType与对象类型文字{(ParamList)完全等效:ReturnType}

    所以我想要的是:

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

    完整的例子:

    var f : (string) => string
    
    f = x => '(' + x + ')';
    
    var h : { (s: string): string; }[]
    
    h = [];
    
    h.push(f);
    

    Update

    this changeset判断,在1.4中的类型声明中将允许使用括号,因此问题中的"first guess"也是正确的:

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

    Further Update 这是1.4!

  • 0

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

相关问题