Takeshi Tokugawa YD
Takeshi Tokugawa YD

Reputation: 923

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?

enter image description here

Upvotes: 1

Views: 43

Answers (2)

kingdaro
kingdaro

Reputation: 12008

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.

Upvotes: 1

HugoTeixeira
HugoTeixeira

Reputation: 4884

You can use the Array class with the Function class in the generics, like this:

private onResizeWindowHandlers: Array<Function>;

Upvotes: 2

Related Questions