简体   繁体   中英

Typescript: how I can use array of functons?

In the below code, onResizeWindowHandles has type any , but must be the array of functions:

export default class PageLayoutManager {

  private $Window: JQuery<Window>;
  private onResizeWindowHandlers: any;

  constructor () {
    this.$Window = $(window);

    this.handleWindowResize();
    this.onResizeWindowHandlers = new Array();
  }

  public addWindowOnResizeHandler(newHandler: any): void {
    this.onResizeWindowHandlers.push(newHandler);
  }

  private handleWindowResize(): void {
    this.$Window.on('resize', () => {
      this.onResizeWindowHandlers.forEach(handlerFunction => {
        handlerFunction();
      })
    });
  }
}

How I can correctly set the type for onResizeWindowHandles ?

在此输入图像描述

您可以在泛型中将Array类与Function类一起使用,如下所示:

private onResizeWindowHandlers: Array<Function>;

Here's the syntax for typing a function, using a type alias

type MyFunc = (arg1: number, arg2: string) => boolean

Alternatively, as an interface:

interface MyFunc {
  (arg1: number, arg2: string): boolean
}

Either work, but I prefer the type alias. It's a little more succinct and readable.

In your case, () => void is probably the most fitting, seeing as the function is being called without arguments, and the return type is unused.

type ResizeHandler = () => void

export default class PageLayoutManager {
  private onResizeWindowHandlers: ResizeHandler[]

  constructor () {
    this.onResizeWindowHandlers = [] // as an aside, use `[]` instead of `new Array()`
  }

  public addWindowOnResizeHandler(newHandler: ResizeHandler): void {
    this.onResizeWindowHandlers.push(newHandler)
  }
}

The type Function would also work here, but it's basically the same as (...args: any[]) => any , which isn't very type safe and should generally be avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM