Using Typescript to Modify Parent Class Properties in Child Class

Consider this scenario:

class Parent {
    propStr = "Hello";
    propNum = 42;

    constructor(propShared) {
        console.log(this.propStr); // Hello
        console.log(this.propNum); // 42
        console.log(propShared); // w/e
    }
}

class Child extends Parent {
    propStr = "Hi"; // overridden
    propNum = 1337; // overridden

    constructor(propShared) {
        super(propShared);
    }
}

let c = new Child("Foobar");

What steps should be taken to ensure that the parent properties are correctly overridden, resulting in the console.log displaying the child's properties?

Answer №1

When logging properties from the parent constructor, they are displayed before any potential child constructor code modifications take place. It is important to remember that initialization should occur within the constructor without executing any side effects:

class Parent {
    propStr = "Hello";
    propNum = 42;

    log() {
        console.log(this.propStr);
        console.log(this.propNum);
    }
}

class Child extends Parent {
    propStr = "Hi"; // overridden
    propNum = 1337; // overridden
}

const c = new Child("Foobar");
c.log()

If you need initialization to be based on external factors or child classes, consider making them parameters with default values:

class Parent {
    constructor(propStr = "Hello", propNum = 42, propShared) {
        this.propStr = propStr;
        this.propNum = propNum;
        this.propShared = propShared;
    }
    log() {
        console.log(this.propStr);
        console.log(this.propNum);
        console.log(this.propShared);
    }   
}

class Child extends Parent {
    constructor(propShared) {
        super("Hi", 1337, propShared);
    }
}

const c = new Child("Foobar");
c.log();

Answer №2

Another approach is to utilize a getter. This way, the parent constructor will access the value defined in the child.

class Mother {
    get message: string {
      return "Greetings"
    }
}

class Offspring extends Mother {
    get message: string {
      return "Salutations"
    }
}

Answer №3

If you're working with typescript, you might find the feature of typescript known as Parameter Properties helpful:

class Parent {
    constructor(public propStr = "Hello", public propNum = 42, public propShared: any) {
        console.log(this.propStr); // Hello
        console.log(this.propNum); // 42
        console.log(this.propShared); // w/e
    }
}

class Child extends Parent {
    constructor(propShared: any) {
        super("Hi", 1337, propShared);
    }
}

let c = new Child("Foobar");

You'll get the expected output by using this 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

Retrieve the JSON object with an AJAX request that contains three arrays, then transfer these arrays to JavaScript

A web page I designed generates the following content: <script> var JSONObject = { "groups":['1210103','1210103','1210103','1210405'], "prices":['279,00','399,00',&ap ...

What are some ways to restrict the number of words per line?

I'm currently developing an online store using NextJS and Material UI. The issue I encountered is related to the long product names that are causing my Card component to stretch. As shown in this image: https://i.sstatic.net/07qNm.png If you obse ...

"Exploring the relationship between Typescript and Angular: transforming variables within different

Ever since I made the switch from JavaScript to TypeScript (Version 2.1.5), I have been facing an issue with the code that filters date selection. Despite my efforts, I haven't been able to find a good fix for it yet. Here are the two date-pickers: F ...

I'm having trouble pinpointing the issue in my code

For some reason, the first button in the div in this code is not working on HTML files. I have tried multiple JavaScript and HTML validators but none of them seem to work. Surprisingly, it works fine on codecademy.com and w3schools.com, but the issue persi ...

Navigate to the specified location using AJAX

When I update a comment using AJAX, I want to automatically scroll down to the updated comment: $("#aggiorna").click(function(){ var value = $("#id").val(); var dato = $("#comment_edit").val(); var dato1 = $("#user_id").val(); var dato2 = ...

Creating separate UI-views using ui-router within a single module

Can two independent ui-views be created using ui-router for a single module? The objective is to have the ui-views "know" where to display the current state, essentially creating a form of redirection. https://i.sstatic.net/OTNNL.png ...

Transforming a React application from ES6 hooks to Class-based components

Hello, I am new to React and currently facing a challenge in converting the following code into a Class Based Component. Despite knowing that I am going in the opposite direction, I am unable to figure out how to proceed without encountering errors. Any ...

Watchable: Yield the outcome of a Promise as long as watching continues

I am looking to create a function in Angular and TypeScript that will return an Observable for subscription. This Observable should emit the result of a Promise every three seconds. Currently, I have a function that returns a Promise, but I need it to ret ...

Consistent value displayed by addEventListener for each event

Hey everyone, I've been experimenting with different solutions for a few hours now but I'm still stuck on this problem. I have a function that takes JSON as input - I can create an 'a' element: CHECK I can set all the element propertie ...

What is the best way to include an item in a list with a specific identifier using the useState Record data type in a React application built with TypeScript?

Here is the structure of my Record type: const PEOPLE_MAP_INIT: Record<string, Person[]> = { "1": [], "2": [], "3": [] }; I have initialized the useState like this: const [PEOPLE_MAP, SET_PEO ...

Provide specific labeling for the y-axis on AM charts

I'm currently utilizing Amcharts to create charts. I am looking to add a label to the Y axis which specifies units (e.g: temperature, marks, etc). Furthermore, I am interested in integrating an image with the label text. Despite going through all doc ...

Trouble retrieving an array within a nested immutable object

Can you do this? render() { var items = this.props.items.course_list; console.log(items); return ( <div> </div> ) } Outcome: https://i.sstatic.net/ugSsN.png Attempt to access course ...

How can I add a comma after every third number in a react component?

I am currently developing an input feature where I need to insert a comma after every 3 numbers, such as (352,353,353). The challenge is to display this format in a text field. Since I am new to working with React, I would appreciate any guidance on how to ...

AngularJS - Error in ui.calendar: Trying to access the length property of an undefined variable leads to a TypeError

I am currently developing a calendar using fullcalendar that retrieves events from an external JSON file. I encountered the following error: TypeError: Cannot read property 'length' of undefined at Object.changeWatcher.getTokens (calendar.js:98) ...

Utilize JSON data in d3.js for creating a scatterplot visualization

I have recently started working with d3.js and I'm facing some challenges. From what I understand, the second parameter passed in d3.json() is used to process data from a JSON file. Here is my code: d3.json(base_url() + "data/data.json", clean_data) ...

Bootstrap Modal for WooCommerce

I'm facing an issue while trying to create a modal window using woocommerce variables ($product). The problem lies in the placement of my modal and accessing the correct product id. Here is the code snippet I've been working on. Unfortunately, i ...

Halt of dispatcher playback occurs after a duration of 10 minutes with discord.js

Currently, I've been working on a music bot using discord.js. To handle audio streaming, I'm utilizing @discordjs/opus and ytdl-core-discord. Everything runs smoothly when testing the bot locally on my machine - songs from YouTube are played with ...

The state object in Redux Toolkit remains static, resulting in the error message "Uncaught TypeError: Cannot assign to read only property 'property-name' of object '#<Object>'"

I'm facing an issue where I am trying to update the data of a state object in Redux Toolkit but it's not changing, and instead throwing an error that says Uncaught TypeError: Cannot assign to read only property 'status' of object ' ...

Kohana ajax causing removal of JQuery Data attributes

Currently, I am developing an application where jquery data is used to pass variables to HTML elements. It has been successful in one part of the site when the data attributes are added to a tr tag. The following code works: <tr class="js-instructions ...

"Utilizing Typescript with Angular NGRX, the actions$.pipe() method can lead to

I am currently facing an issue with ngrx/effects - specifically with a pipe being undefined. I have included a sample code snippet below that appears to be correct according to the compiler, but I am receiving an error in the browser stating that the pipe ...