Typescript issue: variable remains undefined even after being assigned a value in the constructor

In my code, I declared num1: number.

constructor(){
  ...
  this.num1 = 0;
}

This is all inside a class.

However, when I try to log the value of this.num1 or typeof this.num1 inside a function using console.log(), it returns undefined in both cases.

I am confused as to why the value of my variable is coming up as undefined. Can anyone help me understand what might be going wrong?

Answer №1

It has been noted by other commenters that the probable cause is that this is not behaving as expected within the function.

If you have a class structured like this:

class Foo {
    public myValue: number;
    constructor() { this.myValue = 0; }
    barOne() { console.log(this.myValue); }
    barTwo = () => { console.log(this.myValue); }
}

The barOne and barTwo methods will demonstrate different behavior when used as callbacks externally from the class.

This situation arises when utilizing a class instance method as a callback for a button, as in your scenario.

Exploring further into the workings of this in JavaScript and TypeScript (JavaScript behaves similarly to TypeScript if ECMAScript 6 is supported) can provide valuable insights, with numerous informative articles available on the topic.

However, a straightforward solution is to utilize "arrow functions," as demonstrated in the implementation of the barTwo method above.

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

Troubleshooting issue with alignment in Material UI using Typescript

<Grid item xs={12} align="center"> is causing an issue for me No overload matches this call. Overload 1 of 2, '(props: { component: ElementType<any>; } & Partial<Record<Breakpoint, boolean | GridSize>> & { ...

Ensure that the date is valid using Joi without transforming it into UTC format

Is there a method to validate a date using @joi/date without converting it to UTC? I need to ensure the date is valid before storing it in the database. Here's what I've attempted: const Joi = require('joi').extend(require('@joi/ ...

What advantages does subscribe() offer compared to map() in Angular?

I recently started exploring observables in angular2 and found myself puzzled over the decision to use map() instead of subscribe(). Let's say I am fetching data from a webApi, like so: this.http.get('http://172.17.40.41:8089/api/Master/GetAll ...

Using Angular 2 to round a calculated number within HTML

In the HTML code, there is a calculated number associated with Component1. Component1 serves as a tab page within a Bootstrap tab panel. Below is the HTML code with the tab panel: <div id="minimal-tabs" style="padding:75px;padding-top:60 ...

Angular/TypeScript restricts object literals to declaring properties that are known and defined

I received an error message: Type '{ quantity: number; }' is not assignable to type 'Partial<EditOrderConfirmModalComponent>'. Object literal may only specify known properties, and 'quantity' does not exist in type &ap ...

Why is my Angular promise unexpectedly landing in the error callback?

I am facing an issue with my Angular + Typescript client. I have developed a PHP API and need to send a post request to it. Upon receiving the request, the server fills the response body with the correct data (verified through server debugging). However, w ...

Converting TypeScript to JavaScript: A Step-by-Step Guide

I have this code written in Typescript and I need to convert it to JavaScript const Home = (props) => { return ( <div> {props.name ? 'Hi ' + props.name : 'You are not logged in'} </div> ); }; How can I re ...

Upon completion of a promise in an express middleware and breaking out of a loop, a 404 error is returned

In my efforts to retrieve an array of object (car) from express using database functions in conjunction with the stolenCarDb object, everything seems to be working fine. However, when attempting the following code snippet, it results in a 404 error w ...

When utilizing Jest, the issue arises that `uuid` is not recognized as

My current setup is as follows: // uuid-handler.ts import { v4 as uuidV4 } from 'uuid'; const generateUuid: () => string = uuidV4; export { generateUuid }; // uuid-handler.spec.ts import { generateUuid } from './uuid-handler'; de ...

Passing a React functional component with SVG properties to another component as a prop

My goal is to import a React functionComponent from an SVG and pass it as a prop to another component for rendering the svg. The code below compiles without errors, but crashes when trying to display the svg in the browser with the following message: Er ...

Unleash the power of Typescript and Node to create detailed REST API documentation!

Is it possible to generate REST API documentation using https://github.com/TypeStrong/typedoc similar to what can be done with ? I would appreciate any recommendations on leveraging TypeScript types for creating REST API documentation (specifically within ...

Prevent TypeScript from allowing strings or arrays to be assigned to types with no properties

Can we limit the input for param so that it does not allow strings, arrays, etc.? interface bar { x?: number; y?: string; } function qux(param: bar) { } qux("hello"); ...

What could be the reason for mocha failing to function properly in a project that is set up

During a unit test in my TypeScript project using mocha, I encountered an issue when setting the project type to module. The error message displayed is as follows: ➜ typescript-project yarn test yarn run v1.22.17 warning package.json: No license field $ ...

The Angular4 router.navigate function appears to be unresponsive and fails to perform any actions

I have implemented conditional navigation based on the customer's role in the system. Here is an example of how it works: this.GetQuickStartStatus() .subscribe(data => { if(data.isActive){ ...

React router loader is not functioning correctly when trying to fetch data

My attempt to fetch an array of data from an API is resulting in an empty response within the application. However, when I try the same call in a swagger, it returns the correct array. HomePage.tsx: const HomePage = () => { const books = useLoaderDat ...

Stop webpack from stripping out the crypto module in the nodejs API

Working on a node-js API within an nx workspace, I encountered a challenge with using the core crypto node-js module. It seems like webpack might be stripping it out. The code snippet causing the issue is: crypto.getRandomValues(new Uint32Array(1))[0].toS ...

What is the best way to define a function agreement in Typescript?

I have created a function that can return `undefined` only when its argument is also `undefined`, otherwise it will always return a value derived from the argument provided. Here's an example of how the function works: function triple(value?: number) ...

The ListView is not updating correctly as expected

Currently, I am working on a project where I have a Page with a ListView that displays items from an ObservableArray of Expense objects. The issue I am facing is that when I scroll down, the amount property of some Expense rows is not being displayed. Howe ...

Ensure that the string functions as the primary interface

I'm working with an interface that looks like this interface Cat { color: string, weight: number, cute: Boolean, // even though all cats are cute! } Currently, I need to accomplish something similar to this const kitten: Cat = ... Object. ...

Issue: Execution terminated with error code 1: ts-node --compiler-params {"module":"CommonJS"} prisma/seed.ts

Whenever I run npx prisma db seed, I encounter the following error: Error message: 'MODULE_NOT_FOUND', requireStack: [ '/run/media/.../myapp/prisma/imaginaryUncacheableRequireResolveScript' ] } An error occurred during the execution ...