1

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

2 Answers 2

2

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

private onResizeWindowHandlers: Array<Function>;
Sign up to request clarification or add additional context in comments.

1 Comment

Very laconic solution! Thank you!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.