Set the class function to be uninitialized

I'm a little unsure of my TypeScript knowledge. I have a class MyClass with a member variable that is a function, but I don't know what this function will be at compile time. I want to allow external code to set this function dynamically during runtime so it can be called later. Can anyone provide the syntax in TypeScript for initializing the function as null/void/undefined and then checking if it's defined before calling it?

Here's my current code:

import { User } from 'User':
export type UserCallback = (user: User | null) => void;

export class MyClass {
    private userInfoChangedCallback : UserCallback | null = null; // Initializing to null

    setCallback(callback: UserCallback) {
        this.userInfoChangedCallback = callback;
    }

    register = async(username: string, displayName: string, password: string) => {
        // Some operations here...

        if (this.userInfoChangedCallback === null) {   // Checking if it's null
            this.userInfoChangedCallback(new User(username,displayName));
        }
    }

    

Answer №1

It is important to specify that your class member can be of a certain type or null, and then set null as the default value:

private userInfoChangedCallback: UserCallback | null = null

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

Ways to address the Generic Object Injection Sink eslint error (security/detect-object-injection)

I am seeking a solution to resolve this issue without needing to deactivate eslint. Moreover, I am eager to comprehend the cause of the error. const getMappedCard = (cardName: CardName) => { const mappedCards = { Mastercard: <Mastercard /> ...

Is it necessary to create a unit test for a basic operation involving RxJS?

Imagine a straightforward class that triggers a new event to an RxJS subject whenever the window is resized. Disregard any perceived complexities, as the main point is that this class generates an event. export class ResizeService { priv ...

While attempting to send a GET Request in Angular, access to XMLHttpRequest has been denied due to CORS policy restrictions

I am attempting to establish a GET method for my PHP API. Here is the code snippet I am using: export class PerfilComponent { perfil: any; constructor(private http: HttpClient) { } ngOnInit() { const token:string | null = localStorage.getItem(&ap ...

How to handle type errors when using properties in Vue3 Single File Components with TypeScript

I've hit a roadblock while attempting to utilize properties in Vue3. Despite trying various methods, I keep facing issues during the type-check phase (e.g.: yarn build). The project I'm working on is a fresh Vue3-ts project created using Vite. B ...

The submit button seems to be unresponsive or unreactive

As a newcomer to Angular 2 and Typescript, I am in the process of building a web application. I have created several input fields and, following user submission via a button, I want to log the inputs to the console. However, it seems like my button is not ...

Set up Admin SDK using appropriate credentials for the given environment

As someone new to Node.js, Firebase Cloud Functions, and TypeScript, my objective is to create a cloud function that acts as an HTTP endpoint for clients to authenticate with Firebase. The desired outcome is for the cloud function to provide a custom acces ...

Discover an alternative to Events by harnessing the power of Observables to effectively listen for dismiss events in Angular Ionic

Currently, I am utilizing Ionic's inline modal feature that is activated by a boolean value. However, after the modal is closed, the boolean does not automatically reset to zero. The Ionic documentation suggests that developers should monitor the ionM ...

Tips for effectively utilizing URLSearchParams in Angular 5 HttpClient's "get" function

When working with Angular 4.2, I used the Http service and made use of the get method by passing in a URLSearchParams object as the search parameter: this.http.get(url, {headers: this.setHeaders(), search: params}) Now I am looking to upgrade to Angular ...

Error: Unable to locate the reference for "foo" while utilizing TypeScript in combination with Webpack

My Chrome extension is functioning properly when using JavaScript alone. However, when attempting to incorporate TypeScript with Webpack, I encountered an issue where the function foo could not be found. Uncaught ReferenceError: foo is not defined Here ...

Currently focused on developing vertical sliders that can be manipulated by dragging them up or down independently

https://i.stack.imgur.com/NgOKs.jpg# I am currently working on vertical sliders that require dragging up and down individually. However, when I pull on the first slider, all sliders move together. The resetAllSliders button should also work independently, ...

JavaScript Equivalent of Declaration in TypeScript

In my Next JS application, I encountered a situation where a line of code relies on a variable from a script src in the app.tsx page. Here's how it looks: app.tsx: <script src="https://js.stripe.com/v3/"></script> config.ts: de ...

Tips for effectively handling the auth middleware in react.js by utilizing LocalStorage

After making a call to the authentication API, the plan is to save the authentication token in LocalStorage and then redirect to a dashboard that requires token validation for entry. However, an issue arises where the authentication token isn't immedi ...

The DefaultTheme in MaterialUI no longer recognizes the 'palette' property after transitioning from v4 to v5, causing it to stop functioning correctly

Currently in the process of transitioning my app from Material UI v4 to v5 and encountering a few challenges. One issue I'm facing is that the 'palette' property is not recognized by DefaultTheme from Material UI when used in makeStyles. Thi ...

I am having trouble with the Primeng password template suggestions not appearing as expected

The demonstration available at this link is not functioning correctly, unlike the example provided in the documentation at this website. In the StackBlitz demo, the suggestions are not being displayed as expected for the password template. Take a look at ...

Using RxJs in an Angular 2 application to enable row selection in a table by detecting mouse movements

Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz. The row selection functionality is implemented using mouse event handlers (mousedown, mousemove, mouseup). Below is the template ...

Ways to troubleshoot a serverless framework plugin issue

I have scoured the depths of the internet trying to find an answer to my question with no luck... I am eager to tackle a serverless plugin fix, but I'm struggling with how to attach the debugging process to the code. My development environment is vs ...

What is the best way to create a universal function that can return a promise while also passing along event

I created a specialized function that waits for an "EventEmitter" (although it's not completely accurate as I want to use it on other classes that have once but don't inherit from EventEmitter): export function waitEvent(emitter: { once: Function ...

Is there a method available that functions akin to document.getelementbyid() in this specific scenario?

Currently, I am tackling a project that involves implementing a search function. My initial step is to ensure that all input is converted to lowercase in order to simplify SQL calls. However, I have encountered a challenge that is proving difficult for me ...

Starting PM2 with multiple instances can be achieved by following these steps

While running my nodejs code with PM2, I encountered a requirement for multiple instances of nodejs executing the same code. To address this need, I created a script named "myscript.sh": cd ~/myproject PM2_HOME='.pm2_1' /usr/local/bin/node /u ...

Optimal approach to configuring Spring Boot and Angular for seamless communication with Facebook Marketing API

Currently, I am working on a Spring Boot backend application and incorporating the Facebook marketing SDK. For the frontend, I am utilizing Angular 10. Whenever I create a new page or campaign, my goal is to send the corresponding object back to the fronte ...