Do constructors in TypeScript automatically replace the value of `this` with the object returned when using `super(...)`?

I’m having some trouble grasping a concept from the documentation:

According to ES2015, constructors that return an object will automatically replace the value of “this” for any instances where “super(…)” is called. The constructor code must be able to handle and override any return values from “super(…)” with “this.”

This explanation feels a bit unclear to me. Can someone provide more clarity on what exactly is happening here?

Answer №1

The concept of the super "function call" in JavaScript can be quite perplexing. In normal classes where no objects are returned, the keyword this simply refers to the current instance of the class being constructed. When calling super(), it essentially operates on this same reference, resulting in the final constructed object being an instance of the subclass:

class Foo {
    a = 10;
    constructor() { }
}

class Bar extends Foo {
    z: number;
    constructor() {
        super();
        this.z = 1;
    }
}

const b = new Bar();
console.log(b); // Bar: {a: 10, z: 1}
console.log(b instanceof Bar); // true

However, if the superclass does return a value from its constructor, then somehow this in the subclass adopts that value. This allows subsequent references to this to point to the same object returned by the superclass. As a result, the subclass behaves "normally", although the constructed object is not technically an instance of the class:

class Foo {
    constructor() {
        return { a: 10 };
    }
}

class Bar extends Foo {
    z: number;
    constructor() {
        super();
        this.z = 1;
    }
}

const b = new Bar();
console.log(b); // {a: 10, z: 1}
console.log(b instanceof Bar); // false

This leads to the idea that when invoking super(), it's like saying "call the superclass constructor as if it were a function and check if it returns something". If it does, then implicitly assign the result of that function to this. While you can't directly assign to this, this process happens automatically behind the scenes. Observing how super constructors work when downleveling code to an earlier version of JS before the introduction of the class syntax reveals a similar mechanism:

function Bar() {
    var _this = _super.call(this) || this;
    _this.z = 1;
    return _this;
}

In this scenario, the original this is replaced with a new _this variable.

Link to playground code

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

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Unable to activate the AWS IoT security audit using CDK

I'm trying to activate the AWS IoT security audit using a CDK stack, but I'm encountering some issues. Initially, I referred to this documentation for the interfaceAuditCheckConfigurationProperty and implemented the following CDK code to enable ...

What's the reason for Angular's Tour of Heroes HTTP error handler allowing arguments of any type?

While following Angular's tour of hero tutorial, I noticed that the author implemented an error handler for the http service (hero-service). What struck me was the use of 'any' as the type for the error argument in the handler, whereas in ot ...

Integrating Vimeo videos into Angular applications

I am attempting to stream videos using URLs in my Angular application. Every time I try, I encounter the following error: Access to XMLHttpRequest at 'https://player.vimeo.com/video/548582212?badge=0&autopause=0&player_id=0&ap ...

Achieving dynamic key assignment when updating with mongoose in NodeJS and Express

With a multitude of keys requiring updates from a single function, I am seeking guidance on how to dynamically set the key for updating. static async updateProfile(req, res, next) { const userId = req.body.userId; // The key requiring an update ...

Leverage the power of React, Material-UI, and Typescript to inherit button props and incorporate a variety of unique

Looking to enhance the Material-UI button with additional variants like "square." How can I create a prop interface to merge/inherit props? Check out the following code snippet: import React from "react"; import { Button as MuiButton } from "@material-u ...

Tips for creating a Next.js "Link" component with an optional "href" property

I've created a custom React function using typescript for the Next.js Link component. The "href" property is necessary for the "Link" to be used anywhere, so it couldn't be utilized as a button that functions as a submit button in forms. import N ...

Techniques for returning errors to the calling function using async functions

I am currently encountering an error where if "dateofBirth" is not found, an empty object is sent back to the client. How can I change this so that an error object is sent back instead of an empty object? Essentially, I want to send back a catch process. ...

Angular form requests can utilize the Spring Security Jwt Token to allow all options methods

Despite checking numerous sources online, I am facing a persistent issue with my Angular application. The problem arises when using HttpClient along with an Angular interceptor to set headers for authentication in my Java Rest API using JWT tokens. The int ...

The type 'contextPaneTitleText' argument cannot be assigned to the parameter type 'key of RemoteConfig'

I am encountering an issue when using the following code snippet: const contextPaneTitleText = useFeature("contextPaneTitleText").asString(); This code is resulting in an error message: Argument of type '"contextPaneTitleText" ...

Guide on accessing js file in an Angular application

I have a component where I need to create a function that can search for a specific string value in the provided JavaScript file. How can I achieve this? The file path is '../../../assets/beacons.js' (relative to my component) and it's named ...

How can I incorporate an interface and specify a particular type as the return value in TypeScript?

interface Inter{ str:string } function func(){ let v:Inter={ str:'abc' }; return v; } func()//Is there a way to ensure that the type of value returned from `func` is {str:'abc'} without explicitly declaring it i ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

Is it possible to determine the time format preference of the user's device in Angular? For example, whether they use a 24-hour system or a 12-hour system with AM

In Angular, is there a way to determine whether the user's time format is set to 24-hour or 12-hour system? Any help would be greatly appreciated. Thanks! ...

Ways to access the req.user object within services

After implementing an authentication middleware in NestJs as shown below: @Injectable() export class AuthenticationMiddleware implements NestMiddleware { constructor() {} async use(req: any, res: any, next: () => void) { const a ...

The data that has been retrieved is not currently displayed within the Vue table

I'm currently exploring js/vue and I'm attempting to retrieve data from an API. There's a field where the value is used to fetch data from the API based on that keyword. When I check the console log, I can see that the data is being received ...

Encountering [Object] error in Angular's ngbTypeahead functionality

Here is the code for my input field in component.html: <input type="text" class="form-control" [(ngModel)]="searchQuery" [ngbTypeahead]="recommends" name="searchQuery" typeaheadOptionField="user ...

Angular 9: Chart.js: Monochromatic doughnut chart with various shades of a single color

My goal is to display a monochromatic doughnut chart, with each segment shaded in varying tones of the same color. I have all the necessary graph data and just need to implement the color shading. ...

Using Firebase orderByChild to access a nested object in the database

In my current project, I am utilizing a real-time database with the following data structure: { "users": { "1234": { "name": "Joe", "externalId": "384738473847", }, ...

Searching for MongoDB / Mongoose - Using FindOneById with specific conditions to match the value of an array inside an object nestled within another array

Although the title of this question may be lengthy, I trust you grasp my meaning with an example. This represents my MongoDB structure: { "_id":{ "$oid":"62408e6bec1c0f7a413c093a" }, "visitors":[ { "firstSource":"12 ...