Pass values between functions in Typescript

Currently, I have been working on a project using both Node JS and Typescript, where my main challenge lies in sharing variables between different classes within the same file.

The class from which I need to access the max variable is:

export class constUt {
        env: string;
        max: number;

        constructor() {
            this.env = 'dev';
            this.max = 100;
        }
    }
    

And here is the class where I am struggling to retrieve the max variable:

export class callBack {

        private utilsCo = new constUt();

        call = function (err:any, csv:any) {
            console.log(`max constUt: ${this.utilsCo.max}`); //error

            if (err) throw err;
        }
    }
    

My current issue revolves around finding a way to access the max variable inside the call function.

Answer №1

The issue lies not in the sharing of the variable, but in how the function is declared. When you declare the function as a class variable, it creates a function that may not be directly tied to the class declaring it. Essentially, TypeScript struggles to determine the context in which this should refer to.

To resolve this, here are three possible solutions:

  1. Declare it as a class member
export class callBack {

    private utilsCo = new constUt();

    public call(err:any, csv:any) {
        console.log(`max constUt: ${this.utilsCo.max}`); 

        if (err) throw err;
    }
}
  1. Define it as an arrow function (which inherits the context from the class)
export class callBack {

    private utilsCo = new constUt();

    call = (err:any, csv:any) => {
        console.log(`max constUt: ${this.utilsCo.max}`); 

        if (err) throw err;
    }
}
  1. Explicitly specify the context:
export class callBack {

    private utilsCo = new constUt();

    call = function (this: callBack, err:any, csv:any) => {
        console.log(`max constUt: ${this.utilsCo.max}`); 

        if (err) throw err;
    }
}

Each of these declarations carries a nuanced difference.

1 is declared on the class prototype, with all associated implications

2 does not allow its context to change, which may be desirable in this scenario

3 the context is statically typed, providing no runtime guarantees, similar to (1) but unlike (2)

Answer №2

I tested out your code on stackblitz and it seems to be functioning correctly. Here is a version of your code without TypeScript for better comprehension:

To achieve the desired output, simply include the two lines below.

Tip: Remember to capitalize the first letter of the class name to differentiate it from other variables or class instances.

let callback = new CallBack();
    callback.call(null, {});
============================
Your TypeScript code with the additional lines
==============================

// constUt.ts
// ================================

export class ConstUt {
    env: string;
    max: number;

    constructor() {
        this.env = 'dev';
        this.max = 100;
    }
}


// callback.ts
// ================================

export class CallBack {

    private utilsCo = new ConstUt();
    
    call = (err: any, csv: any) => {
        console.log(`max constUt: ${this.utilsCo.max}`); // OUTPUT : max constUt: 100

        if (err) throw err;
    }
}

// Include the following two lines to see the expected result
// Instantiate an object of your callback class and then invoke the call method with the necessary parameters
// Use null if you want to skip the error block execution and avoid throwing an error

let callback = new CallBack();
callback.call(null, {});

Working Example

class ConstUt {
    env;
    max;

    constructor() {
        this.env = 'dev';
        this.max = 100;
    }
}

class CallBack {

    utilsCo = new ConstUt();
    
    call = (err, csv) => {
        console.log(`max constUt: ${this.utilsCo.max}`); // OUTPUT : max constUt: 100

        if (err) throw err;
    }
}

// Include these two lines to view the anticipated outcome

let callback = new CallBack();
callback.call(null, {});

I hope this explanation is helpful.

Best regards, Jignesh Raval

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

Customize the datepicker locale in Valor

Currently, I am working with Angular2 and typescript alongside the Valor datepicker. Unfortunately, the datepicker does not have the necessary locale built-in. After some research, I discovered that the essential JavaScript file containing the locale infor ...

How can we prevent new chips (primeng) from being added, but still allow them to be deleted in Angular 2?

Hey there! I'm currently exploring how to make the chips input non-editable. I am fetching data objects from one component and using the keys of those objects as labels for the chips. Check out my HTML code below: <div class="inputDiv" *ngFor="le ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

What is the best way to verify the type of an object received from request.body in Typescript

Is it possible to check the object type from the request body and then execute the appropriate function based on this type? I have attempted to do so in the following manner: export interface SomeBodyType { id: string, name: string, [etc....] } ...

Is there a more efficient method for invoking `emit` in Vue's Composition API from an external file?

Is there a more efficient way to access the emit function in a separate logic file? This is my current approach that is functioning well: foo.js export default (emit) => { const foo = () => { emit('bar') }; return { foo }; } When ...

The timer functionality in the Angular 2+ component is malfunctioning

This situation is quite perplexing. I have a timer function that works perfectly on all my components except one. Strangely, I can't seem to figure out why this particular component is not cooperating, especially since there are no error messages appe ...

Is it possible for Go's http server to compile TypeScript?

My current setup involves a NodeJS Application that launches an http server and utilizes client side code written in TypeScript with Angular 2. I'm curious if it's possible to achieve the same functionality using Go programming language? I trie ...

Downloading a PDF in a Next.js application

How can I add a button or link that will instantly download my PDF portfolio when clicked? I am currently working on my resume section and would like to provide users with the option to easily download my CV. Is there a way to do this, and if so, how can ...

How to retrieve a variable from an object within an array using AngularJS code

I recently started learning TypeScript and AngularJS, and I've created a new class like the following: [*.ts] export class Test{ test: string; constructor(foo: string){ this.test = foo; } } Now, I want to create multiple in ...

Create a collection of values and assign it to a form control in Ionic 2

How can I set default values for ion-select with multiple choices using a reactive form in Angular? FormA:FormGroup; this.FormA = this.formBuilder.group({ toppings:['',validators.required] }); <form [formGroup]="FormA"> <i ...

Incorporate a fresh element into an object after its initial creation

Hello, I am looking to create an object in JavaScript that includes an array-object field called "Cities." Within each city entry, there should be information such as the city's name, ID, key, and a District array object containing town data for that ...

Mastering Ember with Typescript - crafting action definitions

Trying to set up my first Ember app using TypeScript, I'm facing issues with defining actions. Most tutorials suggest using the @action decorator like this: import { action } from '@ember-decorators/object'; @action sayHello(){ } However, ...

Determine the accurate data type while iterating through a for loop

I am facing an issue where I have around 40 unique actions defined, all with the same parameters except for each being provided with a different schema which is causing the problem type ActionName = 'replaceText' | 'replaceImage'; type ...

Incorporate a personalized Material UI checkbox within a column of the Material React table

Starting out with React, I decided to incorporate Material React Table v2 into my project. My goal is to include a Material UI checkbox that accurately represents the 'Is Active' data in a disabled state. Despite numerous attempts, I have not bee ...

Testing TypeScript functionality within the Eclipse environment with unit tests

Is there a method to test TypeScript code on the Eclipse platform? I'm searching for something similar to JUnit, but most of the tools I've come across are geared towards Visual Studio. ...

Tips for restricting additional input when maximum length is reached in an Angular app

In my Angular 6 application, I am working on implementing a directive that prevents users from typing additional characters in an input field. However, I want to allow certain non-data input keys such as tab, delete, and backspace. Currently, I have an if ...

Unleashing the power of storytelling with React: A guide to creating dynamic story

weather.stories.ts export default { title: 'Widgets/Forecast', component: Weather, } const Template: Story<any> = (args) => <Weather {...args} />; export const Default = Template.bind({}); Default.args = { forecast: { ...

I'm in the process of putting together a node.js project using typescript, but I'm a little unsure about the steps needed to

Currently, I am working on a node.js project that involves compiling with typescript. I recently realized that there is a directory named scripts dedicated to running various tasks outside of the server context, such as seed file operations. With files now ...

Using MUI ClickAwayListener to automatically close the modal upon clicking in React.Js

In order for the modal to work correctly, it should be visible when the 'More' button is clicked and should close when either the More button or any other part of the screen is clicked (excluding the modal itself). I've attempted different m ...

Utilizing Generic Types for Object Parameters

Why am I encountering an error when trying to use a function of type A for a B type one? How can I define a function type with unknown properties? When I attempt to define props in type B as props: Record<string, unknown>, it results in a similar err ...