What function does the super() method serve in TypeScript subclasses?

On top of being irritating and requiring modifications to every child class whenever the parent class is updated...

Answer №1

Let's explore the code provided below:

class A {
    protected total: number;

    constructor(protected num1: number, protected num2: number) {
        this.total = this.num1 + this.num2;
    }
}

class B extends A {
    constructor(num1: number, num2: number) {
        super(num1, num2);
    }
}

In the constructor of class B, the call to super invokes the constructor of class A. When we examine the compiled javascript code:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
    function A(num1, num2) {
        this.num1 = num1;
        this.num2 = num2;
        this.total = this.num1 + this.num2;
    }
    return A;
}());
var B = (function (_super) {
    __extends(B, _super);
    function B(num1, num2) {
        _super.call(this, num1, num2);
    }
    return B;
}(A));

The reason behind explicitly calling super is to ensure that the constructor of class A is executed and members like num1, num2, and total are initialized in instances of class B.

You may wonder why the compiler doesn't automatically call super, and there are a couple of reasons for that:

(1) There may be scenarios where actions need to be taken before invoking super, as shown below:

class A {
    protected sum: number;

    constructor(protected x: number, protected y: number) {
        this.sum = this.x + this.y;
    }
}

class B extends A {
    constructor(x: number, y: number) {
        if (x % 2 === 0) {
            super(x, y);
        } else {
            super(x + 1, y);
        }
    }
}

It's essential to call super prior to accessing this in the constructor of class B.

(2) Explicitly calling super makes it clear that the parent constructor is being invoked, preventing any unexpected behavior.

This requirement only applies to constructors; methods within a class do not need to call their superclass, but you have the option to do so if you wish to inherit functionality from the parent method.

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

Effortless Route Loading in React Using Typescript's AsyncComponent for Dynamic Loading

I have been experimenting with lazy loading routes in React by following the example provided in the documentation for implementing the AsyncComponent class. The tutorial I referenced can be found here. Below is the asyncComponent function written in ES6 f ...

Custom mapped type results in intermediate forms

I've recently developed a type in Typescript that explicitly blocks specific properties from objects/interfaces. This is necessary because Typescript's excess property checking only kicks in when an object literal is directly assigned, not when i ...

What is the best way to pass props to a styled component (e.g., Button) in Material-UI

One of my tasks involves creating a customized button by utilizing the Button component with styled components. export const CustomButton = styled(Button)({ borderRadius: "17px", fontWeight: 300, fontSize: ".8125rem", height: &q ...

Obtain a tuple of identical length from a function

I'm attempting to create a function that returns a tuple with the same length as the parameter tuple passed to it. Although I tried using generics, I am encountering an error when applying the spread operator on the result. My goal is best illustrate ...

Type for the key in array.reduce that is not specific or unique

Given an array of objects, I use the reduce method to transform it into a new format where each key represents a date from the original array. For example, if the array contains objects with dates like {date: '22-02-06-00:55:66', name: 'one& ...

Encountering a Typescript error while attempting to iterate through Enum keys for generating JSX components

I'm really struggling with this problem. Here's a simple enum I have: export enum depositTypes { ACH = 42, Wire = 36, Check = 3, Credit = 2, } I'm trying to create option tags for a select element, like so: Object.keys(depositTyp ...

Rounding Decimals using JavaScript

I am facing the challenge described in this particular query. In most cases, my code works fine to round numbers to two decimal places with the following formula: Math.round(num * 100) / 100 However, there was a peculiar scenario where it failed. When tr ...

The AutoComplete feature of MaterialUI Component fails to function properly even when there is available data

I am facing an issue with my component as it is not displaying the autosuggestions correctly. Despite having data available and passing it to the component through the suggestions prop while utilizing the Material UI AutoComplete component feature here, I ...

Ways to seamlessly change user profile picture on all components without needing to refresh the page

I believe this question pertains to the overall structure of React applications. When it comes to user sessions, I rely on - NextAuth.js All user information (including profile pictures) from NextAuth is saved on Supabase (PostgreSQL) How can I update ...

Unveiling the Mystery of Angular: Why are constructor parameters without access specifiers hidden from view outside the

When I explicitly set an access specifier for a constructor parameter, it becomes visible outside the constructor. For example: constructor(private employeResourceService:EmployeeResourceService ){ //code} ngOnInit(){ this.employeResourceService=unde ...

The issue of declaration merging and complications with nested node_modules

Here is the structure I am working with: @my/app node_modules @types/angular @types/angular-translate @my/library node_modules @types/angular The issue arises from the fact that @types/angular-translate extends the definitions of @types/angular ...

Tips for efficiently handling state across various forms in separate components using only one save button within a React-Redux application

I am currently developing an application that combines a .NET Core backend with a React frontend, using React Hook Form for managing forms. Unlike typical single-page applications, my frontend is not built in such a way. On a specific page of the applicat ...

Execute a selector on child elements using cheerio

I am struggling to apply selectors to elements in cheerio (version 1.0.0-rc.3). Attempting to use find() results in an error. const xmlText = ` <table> <tr><td>Foo</td><td/></tr> <tr><td>1,2,3</td> ...

Steps for passing the :id parameter to an Angular 2 service using routes

Currently, I am trying to find a way to pass a Mac ID into a service using routes in order to filter data efficiently. In my app.html file, there is a dropdown menu where I manually input a list of Mac addresses. Through Angular activated routes, I am atte ...

Can you explain the purpose of the bind function?

I've been diving into the world of Angular2 with TypeScript and stumbled upon a piece of code that has me scratching my head: export var userServiceInjectables: Array<any> = [ bind(UserService).toClass(UserService) ]; Can someone break down ...

Guide on accomplishing masking in Angular 5

I'm curious if it's achievable to design a mask in Angular 5 that appears as follows: XXX-XX-1234 Moreover, when the user interacts with the text box by clicking on it, the format should transform into: 1234121234 Appreciate your help! ...

Invoking a subclass's method within a base class in Typescript

Currently, I am in the process of developing a small game project and I am facing a particular challenge that I need a solution for. Within my code, I have a base class called 'Entity' which contains essential methods for its subclasses (objects ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...

Display or conceal a button in Angular 6 based on certain conditions

In my current project, I am facing a challenge where I need to disable a button while a task is running and then activate it once the task is complete. Specifically, I want a syncing icon to spin when the task status is 'In_progress' and then hid ...

Display an API generated popup list using Vue's rendering capabilities

I'm attempting to generate a pop-up within a displayed list using custom content retrieved from an API request. Currently, my code looks like this: <template> <div class="biblio__all"> <a v-for="i in items" ...