In TypeScript how do I declare an array of functions that accept a string and return a string?

后端 未结 2 1178
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 01:34

UPDATE - the context of this question was pre-TypeScript 1.4. Since that version, my first guess has been supported by the language. See the update to the a

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 02:02

    I figured it out. The problem is that the => for a function type literal is itself merely syntactic sugar and doesn't want to compose with [].

    As the spec says:

    A function type literal of the form

    ( ParamList ) => ReturnType

    is exactly equivalent to the object type literal

    { ( ParamList ) : ReturnType }

    So what I want is:

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

    Complete example:

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

    Update:

    Judging from this changeset parentheses will be allowed in type declarations in 1.4, so the "first guess" in the question will also be correct:

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

    Further Update It is in 1.4!

提交回复
热议问题