When an abstract method is invoked within the constructor of an abstract class, it does not have access to properties of

This code snippet is supposed to display 'Hello World!' on the screen, but instead it shows an error message:

Error: Cannot read property 'id' of undefined
. What could be the reason behind this issue?

abstract class Parent {
  constructor() {
    console.log(this.getData());
  }

  abstract getData(): string;
}

class Child extends Parent {
  constructor(private item: any) {
    super();
  }

  getData(): string {
    return this.item.id;
  }
}

new Child({id: 'Hello World!'});

Click here for a functional example.

Answer №1

The issue lies in the sequence of events where the call to getData is made within the Parent constructor prior to the assignment of the parameter item to the private field item. This occurs because the automatic initialization happens after the super() call, and not before it. Please refer to the "***" comments for clarification:

abstract class Parent {
  constructor() {
    console.log(this.getData());  // *** Calls Child's getData
  }

  abstract getData(): string;
}

class Child extends Parent {
  constructor(private item: any) {
    super();                       // *** Calls Parent's constructor
    // ** Automatic initialization takes place here, *after* the `super()` call
  }

  getData(): string {
    return this.item.id;           // *** Therefore, `this.item` becomes `undefined` at this point
  }
}

new Child({id: 'Hello World!'});

This highlights one of the reasons why invoking methods from constructors may not be considered best practice: They are subject to being overridden by child classes, but the initialization of the child class may not yet be complete (as seen in this case).

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

Enhance JSON for efficiency in Typescript Mapping

In my Java to Typescript data transfer, I am encountering an issue with objects containing "Map" properties. To define my Typescript models, I use interfaces instead of classes: export interface Foo { bar: Map<string, Bar>; mapOfBar: Map< ...

Organize by a collection of strings or a collection of enums

Here is a list of objects that I have: enum MealType { Breakfast, Lunch, Dinner } interface FoodItem { name: string, type: MealType[], } const foodItems: FoodItem[] = [ { name: 'Pizza', type: [MealType.Lunch, MealType.Dinner ...

When canActivate returns false, the screen in Angular 2 will still be accessed

I am encountering a problem where my canActivate method is returning false, but still navigating to the blocked screen. This issue seems to only occur in Chrome, as everything works fine in IE. Here is how the canActivate method looks: canActivate(route: ...

What is the best way to incorporate CSS from node_modules into Vite for production?

I have a TypeScript web application where I need to include CSS files from NPM dependencies in index.html. Here is an example of how it is done: <link rel="stylesheet" type="text/css" href="./node_modules/notyf/notyf.min.css&quo ...

Exploring the world of Unicode in Angular

I need to search for pokemon and retrieve all Pokémon results (with the accent included) This is my array: let games = ['The Legend of Zelda', 'Pokémon', 'Chrono Trigger'] This is how I am attempting to do it: Using HTML ...

Creating a generic class in Typescript that can only accept two specific types is a powerful

When designing a generic class, I am faced with the requirement that a property type must be either a string or number to serve as an index. If attempting something like the code snippet below, the following error will be triggered: TS2536: Type 'T ...

What is the best way to retrieve paginated data from a simulated JSON server (json-server)?

Looking to return a page using JSON server found at https://github.com/typicode/json-server. The current JSON structure appears as follows: records :[ { id: '2', name: 'k', }, { id:'3', name:'j' } ] Successfully abl ...

What is the best way to inject a service instance into the implementation of an abstract method?

In my Angular application, I have a service that extends an abstract class and implements an abstract method. @Injectable({ providedIn: 'root', }) export class ClassB extends ClassA { constructor( private service : ExampleService) { s ...

Every time you try to import a config.json file in Typescript, it never fails

I have the most recent version of Visual Studio Code installed. Visual Studio Code is currently utilizing TypeScript v3.3.3. I've successfully installed the following packages via npm, both locally (save-dev) and globally: TestCafe v1.1.0 Core-JS v ...

The input 'Query' cannot be matched with the type '[(options?: QueryLazyOptions<Exact<{ where?:"

Using codegen, I've created custom GraphQL hooks and types. query loadUsers($where: UserFilter) { users(where: $where) { nodes { id email firstName lastName phoneNumber } totalCount } } export functio ...

Issue with dispatching actions in React using TypeScript and hooks

Can you please point out what I'm doing wrong here: I am encountering the following error Type '{ wishList: any; addBookToWishList: (book: any) => void; }' is not assignable to type '{ wishList: never[]; }'. Object literal may ...

Session is not functioning properly as anticipated

import * as express from 'express'; import * as session from 'express-session'; import * as bodyParser from 'body-parser'; const app: express.Express = express(); app.use(bodyParser.json()); app.use(session({ secret: &apos ...

angular displaying incorrect values for counter

Hi there, I am new to using Angular and I'm currently facing an issue with increasing and decreasing product quantity on the cart page. The problem is that in my first index it works fine, but in the second index, the value starts with the first index ...

Error involving ESLint detecting unused variables within a TypeScript generic type

My dilemma lies in the implementation of a straightforward object class designed to restrict potential values to a specific type: export class Dictionary<T> { [key: string]: T } Unexpectedly, ESLint is flagging this code with the message 1:25 e ...

How to display an object in the template that does not have a specified property

I am dealing with an object that can have a type of WithBalance | WithoutBalance withBalance : { balance:number, name:string } withoutBalance : { name : string} <span>{{object?.balance ?? 0}} </span> However, when I attempt to access the bal ...

Steps for generating a fresh type denotation from a value within an object

Is it possible to create a new type alias based on an object's values? const test = { 'a': ['music','bbq','shopping'], 'b': ['move','work'] }; How can we extract this information f ...

Exploring the Depths of JSON Arrays within Typescript

I am faced with a challenge in extracting the value of the "id" from the following array of JSON data. The issue lies in the fact that the value is enclosed within double square brackets "[[" which are causing complications in retrieving the desired result ...

Enhance your material-ui component using TypeScript functionality

Exploring ways to enhance the Material-ui Button component by introducing new props. The objective is to introduce a new prop called fontSize with three size options - small, medium, large. <Button variant="outlined" color="primary" ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...

I am hoping to refresh my data every three seconds without relying on the react-apollo refetch function

I am currently working with React Apollo. I have a progress bar component and I need to update the user's percent value every 3 seconds without relying on Apollo's refetch method. import {useInterval} from 'beautiful-react-hooks'; cons ...