Using an array of functions in Typescript: A simple guide

The code below shows that onResizeWindowHandles is currently of type any, but it should be an 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();
      })
    });
  }
}

What is the correct way to define the type for onResizeWindowHandles?

https://i.stack.imgur.com/Sad0P.png

Answer №1

To implement generics in TypeScript, you can utilize the Array and Function classes like so:

private resizeHandlers: Array<Function>;

Answer №2

Below is the syntax for creating a function using a type alias:

type CustomFunction = (param1: number, param2: string) => boolean

Alternatively, you can define the function using an interface:

interface CustomFunction {
  (param1: number, param2: string): boolean
}

Both approaches are valid, but personally, I find the type alias to be more concise and easy to understand.

In this scenario, using () => void may be the most suitable type since the function doesn't take any arguments and does not have a return value being utilized.

type EventListener = () => void

export default class EventHandler {
  private eventListeners: EventListener[]

  constructor () {
    this.eventListeners = [] // Note: use `[]` instead of `new Array()`
  }

  public addEventListener(newListener: EventListener): void {
    this.eventListeners.push(newListener)
  }
}

You could also use Function as the type, but it's essentially equivalent to (...args: any[]) => any, which lacks type safety and should be used with caution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating typescript definitions for Polymer 2.4 packages

According to information provided in the latest announcement, declarations are now automatically generated from the Polymer source. I recently upgraded to Polymer 2.4 and encountered an error during project build due to a missing typescript definition fil ...

In Typescript, is it correct to say that { [key: string]: any } is identical to { [key: number]: any }?

Recently diving into Typescript has been an interesting journey, especially when stumbling upon weird language behaviors. After writing the following code snippet, I was surprised to see that it compiled and executed successfully: let x: { [key: string]: a ...

Sending a POST request to an API with Angular and passing an object as the payload

I'm currently working on adding a feature to my app where I can take the products from an order and send them to the cart, essentially replicating the entire order. While I have successfully retrieved the order, I am facing difficulty in sending it b ...

What is the best way to implement React ErrorBoundary in conjunction with redux-observable?

When dealing with asynchronous code, React Error Boundaries may not function as expected. In my case, I am using redux-observable and rxjs to retrieve data from an API. To handle errors, I am trying to utilize the catchError function provided by rxjs. I ...

Utilizing Angular 10 to Transform a JSON Data into a Custom String for HTML Rendering

I have received a JSON response from my backend built using Spring Boot. The "category" field in the response can either be 1 or 2, where 1 represents Notifications and 2 represents FAQs. { "pageNumber": 0, "size": 5, "totalPages&q ...

The TypeScript script does not qualify as a module

Just starting out with TypeScript and encountering a simple issue. I'm attempting to import a file in order to bring in an interface. Here's an example: Parent: import { User } from "@/Users"; export interface Gift { id: number; ...

"Enhance your forms with RadixUI's beautiful designs for

New to Radix UI and styling components, I encountered difficulties while trying to adapt a JSX component to Radix UI: Utilizing Radix UI Radio Groups, I aim to style my component similar to this example from Hyper UI with grid layout showing stacked conte ...

What is the functionality of the node class within a doubly linked list?

Within the Node class, the next property can only be assigned a value of type Node or null. class Node { value: any; next: Node | null; prev: Node | null; constructor(value: any) { this.value = value; this.next = null; this.prev = null ...

operating efficiently even when producing an incorrect output type

Exploring Typescript for the first time on Codepen.io has left me puzzled. I'm unsure why, despite defining the function signature and return type with an interface, I am able to return a different type without encountering any errors. Is there somet ...

Instantiate a child class within an abstract class by utilizing the keyword "this"

Within my code, there is an abstract class that uses new this(). Surprisingly, this action is not creating an instance of the abstract class itself but is generating an instance of the class that inherits from it. Even though this behavior is acceptable i ...

Tips for utilizing single quotation marks while logging multiple variables in console

When I write console.log("entered values are "+A+" and "+B); the tsLint gives a warning that single quotes should be used. However, I discovered that if I use single quotes, I am unable to include multiple variables in the same console ...

Enhancing Security and Privacy of User Information with JWT Tokens and NgRx Integration in Angular Application

I'm facing a security concern with my Angular application. Currently, I store user details like isAdmin, isLoggedIn, email, and more in local storage. However, I'm worried about the risks of unauthorized updates to this data, especially since my ...

Learn how to efficiently disable or enable a button in Angular depending on the selected radio button

In order to disable the button when the remarks are marked as failed. Here is an example scenario: Imagine there is an array containing two to four items. First example: ITEM 1 -> FAILED -> Remarks (required) ITEM 2 -> FAILED -> Remarks (r ...

Exploring how process.argv in NodeJS can be utilized within JavaScript code compiled by

I'm having trouble compiling a basic TypeScript file using webpack (with 'awesome-typescript-loader') that needs to access command line arguments. It seems like the compiled JavaScript is causing a problem by overriding the Node 'proce ...

issue occurring after inserting a new parameter

I encountered an issue with my test case after adding a new parameter tiger to the method swimming. Despite passing the new parameter tiger to my test case, it continues to break. Update: I am receiving an "undefined grid" error at this line. Any suggest ...

Use PipeTransform to apply multiple filters simultaneously

Is it possible to apply multiple filters with PipeTransform? I attempted the following: posts; postss; transform(items: any[]): any[] { if (items && items.length) this.posts = items.filter(it => it.library = it.library ...

Obtaining context from a higher order component in the constructor of a child component: tips and tricks

In order to gain access to context throughout the application, I've implemented the following context provider: import React, { Component, useContext } from 'react'; import { appInitialization, Context } from "@microsoft/teams-js"; ...

The use of `super` in Typescript is not returning the expected value

Trying to retrieve the name from the extended class is causing an error: Property 'name' does not exist on type 'Employee'. class Person { #name:string; getName(){ return this.#name; } constructor(name:string){ ...

Are all components in Next.js considered client components by default?

I have created a Next.js app using the app folder and integrated the Next Auth library. To ensure that each page has access to the session, I decided to wrap the entire application in a SessionProvider. However, this led to the necessity of adding the &apo ...

What is the best way to explain a function that alters an object directly through reference?

I have a function that changes an object's properties directly: function addProperty(object, newValue) { object.bar = newValue; } Is there a way in TypeScript to indicate that the type of object is modified after calling the addProperty function? ...