The sequence for initializing properties in Typescript

In my Typescript code, I have 2 classes named A and B. Class B inherits from class A, where class A's constructor calls a function called init, and class B overrides the init function. a.ts

export default class A {
    constructor() {
        this.init();
    }

    init() {
        console.log("A.init()")
    }
}

b.ts

import A from "./a"

export default class B extends A {
    public bx = 3;
    public by = 10;
    public bz = 0;
    constructor() {
        super();
    }

    init(){
        this.bx = 5;
        this.bz = this.by;
        console.log("B.init()")
    }
}

When compiled with tsc, the resulting js files looked like this:

a.js

export default class A {
    constructor() {
        this.init();
    }
    init() {
        console.log("A.init()");
    }
}

b.js

import A from "./a";
export default class B extends A {
    constructor() {
        super();
        this.bx = 3;
        this.by = 10;
        this.bz = 0; //even worse
    }
    init() {
        this.bx = 5;
        this.bz = this.by;
        console.log("B.init()");
    }
}

One might question why there is a line this.bx = 3; after super() in the constructor of b.js. It seems redundant since the property should already be initialized. This optimization could be handled better by the compiler to avoid unnecessary assignments.

Comparing to c# code:

using System;
                    
public class Program
{
    public static void Main()
    {
        B b = new B();
        Console.Out.Write("x: " + b.x + " y: " + b.y);
    }
}

class A {
    public A() {
        init();
    }
    
    public virtual void init() {
    }
}

class B : A {
    public int x = 3;
    public int y = 10;
    public int z = 4;
    public B() : base() {
    }
    
    public override void init() {
        this.x = 5;
        this.y = this.z;
    }
}

You will get x: 5 y: 4.

Answer №1

It is crucial to make sure that your base class is fully initialized before initializing the extended subclass, as stated in the MDN documentation for super:

In a constructor, the super keyword should be used before the this keyword

If the base class calls an overridden method in its constructor that manipulates properties of this in the subclass, the initialization order is disrupted. This violation breaks any assumptions made by compilers based on this requirement.

This can lead to chaos...

The best scenario would be a clear compilation error.

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

Using TypeScript, extract the value of a Promise from a Page Object

Struggling to retrieve a value from a WebDriver promise in a Protractor solution using TypeScript, the response keeps coming back as undefined. get nameInput(): string { var value: string; this.nameElement.getAttribute('value').then(v =& ...

Guide on simulating rxjs/Websocket in angular for performing Unit Testing

I have developed a service that manages websocket communication with a server and I am looking to create unit tests for it. However, I am facing challenges in mocking rxjs/Websocket. While searching for a solution, I came across a similar question here, b ...

What is the best way to invoke a method from a class in Angular testing when the class has a Router constructor?

Currently, I am in the process of creating a test case for my authentication service outlined below. AuthService.ts import {Subject} from 'rxjs'; import {User} from './user.model'; import {AuthData} from './auth-data.model' ...

Is there a way to seamlessly transition between different Angular components without having to refresh the entire webpage?

I'm currently working on implementing a navigation bar that allows users to switch between three components without having the navbar reload. The goal is for only the new component to load when the user clicks on a different section of the navbar, kee ...

I encountered an issue with my autocomplete feature in Angular TypeScript where it was returning a [object Object] value

Issue with autocomplete displaying [object Object] value in Angular TypeScript I'm having trouble pinpointing the exact problem HTML snippet <mat-form-field style="margin-right: 10px;"> <input #productName matInput placeholder="Product" ...

Can a function utilize a Generic-specified type property?

function extractStringValue<T extends object, S extends keyof PickByValue<T, string>>( obj: T, key: S ): string { return obj[key]; }; The PickByValue function extracts properties of object T with values of type string. type CustomType = ...

tips for accessing the useState value once it has been initialized

When using the state hook in my code, I have: const [features, setFeatures] = useState([]) const [medicalProblem, setMedicalProblem] = useState([]) The medicalProblem variable will be initially populated with a response from an API call: useEf ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

Angular FormData fails to append and upload files

I am attempting to use FormData in order to upload a file through an HTTP Request. Here is the HTML code: <ng-template #displayApp> <div class="display flex justify-content-center"> <div > <p-fileUploa ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

How can I display and link a base64 string to an Image as a source in Nativescript?

I'm having trouble displaying and binding a base64 image as an ImageSource in my View. The image doesn't show up at all, and I couldn't find any helpful information about it in the documentation. Am I missing something? The imageSource prop ...

Controlling numerous websockets using React

I am currently developing a single-page application using React.js with a JSON RPC 2.0 backend API that relies on websockets. Managing multiple websocket connections simultaneously across different React.js components has been a challenge. Initially, I th ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Resetting the initial values in Formik while utilizing Yup validation alongside it

Currently, I am working on a React application with Typescript and using Formik along with Yup validation. However, I have encountered an issue with setting values in a Select element. It seems that the value is not changing at all, or it may be resettin ...

After filling a Set with asynchronous callbacks, attempting to iterate over it with a for-of loop does not accept using .entries() as an Array

Encountering issues with utilizing a Set populated asynchronously: const MaterialType_Requests_FromESI$ = SDE_REACTIONDATA.map(data => this.ESI.ReturnsType_AtId(data.materialTypeID)); let MaterialCollectionSet: Set<string> = new Set<s ...

Utilizing const as the iteration variable in a for loop

I've grasped the concept of using var and let in a for loop in typescript/javascript, but can someone shed light on how and why a const variable as a loop variable behaves? for (const i = 0; i < 5; i++) { setTimeout(function() { console.log( ...

One efficient way to iterate through an object and modify its values in a single line of code

_shop: { [key: string]: string[] } = { fruits: ['Apple', 'Orange'], vegetables: ['Tomato', 'Onions'] } Can a one-liner code be used to modify the values of _shop and return it in a specific format? The desired outp ...

What is the process for creating a method within a class?

Here is the current structure of my class: export class Patient { constructor(public id: number, public name: string, public location: string, public bedId: number, public severity: string, public trajectory: number, public vitalSigns: ...

Callback after completion of a for loop in Angular TypeScript

During the execution of my javascript async function, I encountered a situation where my printing code was running before the div creation. I needed to ensure that my print code would run only after the completion of the for loop, but I struggled to find a ...

Trouble with displaying cell content in ag-grid within an Angular application

I have implemented ag-grid in my Angular project and I am trying to redirect to a link when a specific cell is clicked. Currently, I have a new value coming from an API which is nested inside an object in an array. For example, the object is dto-> dat ...