A Typed array of functions

前端 未结 4 2079
生来不讨喜
生来不讨喜 2021-02-02 05:28

I\'m struggling to figure out if it\'s possible in TypeScript to declare a statically typed array of functions.

For example, I can do this:

foo: (data:st         


        
相关标签:
4条回答
  • 2021-02-02 05:38

    Other (newer, more readable) ways to type an array of functions using fat arrows:

    let foo: Array<(data: string) => void>;
    let bar: ((data: string) => void)[];
    
    0 讨论(0)
  • 2021-02-02 05:40

    You can find this in the language spec section 3.5.5:

    foo: { (data: string): void; } []
    
    0 讨论(0)
  • 2021-02-02 05:46

    or foo: ((data: string) => void)[]

    0 讨论(0)
  • 2021-02-02 05:56

    If you wish declare an array of callable function in TypeScript, you can declare a type:

    type Bar = (
      (data: string) => void
    );
    

    And then use it:

    const foo: Bar[] = [];
    
    const fooFn = (data: string) => console.log(data);
    foo.push(fooFn);
    foo.forEach((fooFn: Bar) => fooFn("Something");
    
    0 讨论(0)
提交回复
热议问题