Issues with replicating Typescript

Hey there, I'm encountering an issue with TypeScript. Here is the code snippet:

class A {
    constructor() {
        this.initialize();
    }

    public initialize() {
        console.log('a')
    }
}

class B extends A {
    constructor(public text) {
        super();
    }
    
    public initialize() {
        console.log(this.text)
    }
}

new B('text');

When I run this code, the console displays 'undefined'. Can anyone suggest a solution to address this problem?

Answer №1

The reasoning behind this occurrence is due to the fact that the super() method is the first one invoked when you create a new instance of B by calling new B('text'). When super() is called, it immediately triggers this.init(). Since this refers to an object of type B, not A, it attempts to execute console.log(this.text) instead of console.log('text'). However, at the point of this operation, this.text has not yet been assigned a value as it happens after the call to super.

This underscores the importance of avoiding performing tasks within the constructor. Your object is not fully functional until the constructor has completed its execution.

To address this issue, it is recommended to remove the init() call from the parent's constructor and invoke it separately like this:

class A {
    public init() {
        console.log('a')
    }
}

class B extends A {
    constructor(public text: string) {
        super(); // no longer necessary since the parent class has no constructor.
    }

    public init() {
        console.log(this.text)
    }
}

const b = new B('text');
// Object is now ready for use.
b.init();

Answer №2

class B extends A {
    public content:string;
    constructor(public content) {
        super();
        this.content = content;
    }
    public start() {
        console.log(this.content)
    }
}

give it a shot

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

Ionic app experiencing a CORS dilemma post-build

Using Ionic 3, I have written a provider code to fetch data from an API endpoint hosted on an HTTPS server. For example, my endpoint is located at . Below is the code for my provider: // Provider Class Function load(){ if(this.data){ return Pro ...

Encountering an issue with accessing a property in Angular's TypeScript module

I encountered an issue while trying to access a property of a static array that I created in a TypeScript class. The error message I received is as follows: ERROR TypeError: Cannot read property 'forbiddenProjectNames' of undefined Below is th ...

I am interested in showcasing a distinct screen layout specifically designed for mobile device viewing

Looking to display different screens for PC and smartphone users. I am using react, Typescript, and next.js for development. Specifically, I need to show user.tsx when accessing the /user URL from a PC, and Accessdenied.tsx when accessing it from a smartp ...

Generic TypeScript any object that is plain

update I have included my current code to better illustrate the problem: https://gist.github.com/LukasBombach/7bf255392074509147a250b448388518 Using TypeScript, I aim to define a generic that represents any plain object data structure class MyClass<T ...

Importing modules in NodeJS can lead to errors related to types

Following TSLint's recommendation to avoid using the var keyword in TypeScript, I have opted to use import for importing modules. However, this approach has led to errors when trying to utilize local modules. In the file routes/main.ts, my code looks ...

Guide on effectively testing the catch block of a Typescript function using mocha and chai

In my TypeScript class, I have implemented several functions, each containing a try-catch block that returns a predetermined response upon encountering an error. While writing unit tests using Mocha and Chai, I am facing difficulties in intentionally trig ...

What is the process for importing JSON from an NPM package in Angular version 15?

I've been dealing with a local package that contains a json file, and my current challenge is to load this json file into the Angular 15 app.component.ts. To bring the json file package into my Angular project, I followed this installation process: n ...

What is the functionality of ngModel in the Angular Heroes Tour tutorial?

Hello everyone, this is my first post here. I have been diving into the Angular Tour of Heroes using Angular 6 and I think I understand how ngModel works, but there's one thing that puzzles me. How does it manage to update the data in my list when th ...

Incorporating Bootstrap Modal into a TypeScript-based minimalist web application

I want to incorporate the Bootstrap Modal component into my TypeScript application. Therefore, I added the necessary types: npm i @types/bootstrap After that, in my TypeScript code: import { Modal } from "bootstrap"; const myModal = new Modal(&a ...

It is not possible to transform Next.js into a Progressive Web App (P

Can someone assist me with PWA implementation? I tried running npm run build, but it was unsuccessful. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdbaacbface0abbfa2a3b98dfde3fce3fd">[email protected]</a> ...

Tips for adjusting the size of icons in Ionic Framework v4 and Angular 7

The library ngx-skycons offers a variety of icons for use in projects. If you're interested, check out the demo here. I'm currently incorporating this icon library into an Ionic project that utilizes Angular. While the icons work perfectly, I&ap ...

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 on how to effectively unit test error scenarios when creating a DOM element using Angular

I designed a feature to insert a canonical tag. Here is the code for the feature: createLinkForCanonicalURL(tagData) { try { if (!tagData) { return; } const link: HTMLLinkElement = this.dom.createElement('link'); ...

Explaining the data link between a service and component: understanding Subject and BehaviorSubject

Can someone explain the concepts of Subject and BehaviorSubject in Angular to me? I'm new to Angular and struggling to understand. I've tried searching online, but I still can't grasp how they work. The same goes for Observable and Observer ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...

Do I need to use [providers] when implementing constructor dependency injection?

Currently following a step-by-step guide on managing tasks and it includes the following code snippet: import {TodoDataService} from './todo-data.service'; @Component({ // ... providers: [TodoDataService] }) constructor(private todoDa ...

Encountering an issue with a custom hook causing an error stating "Attempting to access block-scoped variable 'X' before its declaration."

Currently, I am in the process of developing my initial custom hook. My confusion lies in the fact that an error is being displayed, even though the function is defined just a few lines above where it's invoked. Here is the relevant code snippet: f ...

Tips for managing a stored data reservoir with react-query

I am looking to develop a unique custom hook that can effectively manage a cache and fetch only new items. Here is the expected behavior: Upon initial request for [1, 2, 3, 4, 5], it should fetch all [1, 2, 3, 4, 5] as the cache is empty. If a request is ...

Typescript is failing to pick up process.env variables and is treating them as undefined, even though they are

I thought that by adding environment variables to environment.d.ts, they would have the correct types. I am using @types/node as a dev-dependency, and I have defined DATABASE_URL in my environment.d.ts like this: declare global { namespace NodeJS { ...

Can Tailwind Merge function apply to Tailwind classes with prefixes?

When dealing with conflicts, I am required to use tailwind classes with a prefix. However, the tailwind merge functionality does not seem to work with prefixed classes such as tw-flex-1 instead of flex-1. During debugging, I attempted the following: conso ...