Tips for effectively overriding a method in typescript

Why is this.fullName appearing empty in the show() method?

class Person {
  protected name: string = "";
  constructor(name: string) {
    this.makeSir(name);
  }

  makeSir(name: string) {
    this.name = "sir" + name;  
  }
}

class Man extends Person {
  protected fullName = "";
  constructor(name: string) {
    super(name);
  }

  makeSir(name: string) {
    super.makeSir(name);
    this.fullName = "***" + name;
    console.log(this.fullName);//[LOG]: "***john" 
  }

  show() {
    console.log(this.fullName);//[LOG]: "" 
  }
}


const man = new Man("john");
man.show();

What steps can be taken to resolve this issue?

Answer №1

super() is always the first function called when creating a subclass like your Man. It runs before any variable assignments, such as protected fullName = ''. So, while you're setting fullName in Man.makeSir, the empty string assignment overrides it right after.

To prevent this from happening, you can avoid giving an initial value to fullName:

// specify a type without assigning an initial value
// use '!' syntax to indicate to TypeScript that this will be initialized in the constructor
// even if TS cannot deduce that itself
protected fullName!: string;

By not setting an "initial" value for fullName, you preserve the changes made by the super() call.

Answer №2

class Individual  {
    
protected identity: String ="";
    
    constructor(identity: string){
        this.assignTitle(identity);
    }
    
    assignTitle(identity: string){
        this.identity="sir"+identity ;
    }
    
    customFunction(){
        console.log("INDIVIDUAL");
    }
}

class Human extends Individual {
    public identity: string ="";
    
    constructor(identity:string){
        super(identity);
        this.assignTitle(identity);
    }
    
    assignTitle(identity:string){
        this.identity="####"+identity;
    }
    
    customFunction(){
        console.log("Human ")
    }
    displayInfo(){
        console.log("#####"+this.identity);
    }
}

const h = new Human("Being ")
h.displayInfo();
h.customFunction();


const i = new Individual("Special");
i.customFunction();

You are only invoking super in the constructor, which then calls the superclass constructor.

If you notice, the test function is properly overridden

Output:

#########Being 
Human 
INDIVIDUAL

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

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

Integrating Constant Contact API into a Next.js application

I'm trying to integrate the Constant Contact API into my Next.js application. I've looked through the documentation, but it only provides examples for PHP and Java. How can I effectively use the authentication flow and create an app on the dashbo ...

Guide on navigating an array of objects using the provided keys as a starting point in Javascript/Typescript

Assuming I have an array of objects structured like this: const events: Array<{year: number, month: number, date: number}> = [ {year: 2020, month: 10, date: 13}, {year: 2021: month: 3, date: 12}, {year: 2021: month: 9, date: 6}, {year: 2021: mont ...

Using Symbol.iterator in Typescript: A step-by-step guide

I have decided to upgrade my old React JavaScript app to React Typescript. While trying to reuse some code that worked perfectly fine in the old app, I encountered errors in TS - this is also my first time using TS. The data type I am exporting is as foll ...

Error message on Cypress with TypeScript: No test specification files detected

Encountering the error "Unable to run because no spec files were found, even though there is a .ts spec file in Cypress. Execute the command below in the terminal: npx cypress run --spec="./cypress/integration/specs/Test1.spec.ts". Attempted to run the t ...

Stop redux useSelector from causing unnecessary re-renders

I'm working on a component in React-Redux that utilizes the useSelector hook to retrieve a dictionary from the Redux store. This dictionary maps UUIDs to objects containing data that I need to display. interface IComponentProps { id: string } const ...

Determine the implicit type of the assigned function, while also constraining the return type to be a subtype of a predefined

When writing multiple functions for server requests, I have encountered a dilemma with TypeScript. Each function must return a type that extends a specific predefined known type, but I also want TypeScript to infer the most accurate return type possible. ...

Angular Universal causing issues with updating the DOM component

@Component({ selector: 'mh-feature-popup', template: ` <div class="full"> <div> <div class="container-fluid" [@featurepop]="state"> <div class="row"> <div class="col-xs-12 col-md-4 col-md-offse ...

Having trouble finding the "make:migration" command in Adonis 5 - any suggestions?

After reviewing the introductory documentation for Adonis Js5, I attempted to create a new API server. However, when compiling the code using "node ace serve --watch" or "node ace build --watch", I kept receiving an error stating "make:migration command no ...

formik connects props that are lacking certain properties

Trying to figure out a way to simplify the process of declaring all the properties of formik in my Props when using connect(). The error message I keep encountering is: Type '{ entry: Entry; }' is missing the following properties from type &apos ...

Leveraging async/await in Firebase functions along with the once() method

Recently diving into the world of TypeScript, I've been navigating my way through with relative ease. However, I've encountered a perplexing issue while working with async/await. The problem lies within this code snippet - the 'await' ...

The rapid execution of code causing an observable race condition

When exporting a CSV file in my code, I encounter a race condition while trying to modify some data before the export. The issue is that the id gets set correctly, but the number only updates after the method is called a second time. I believe the proble ...

Apologies, but there was an error attempting to differentiate 'nombreyo'. Please note that only arrays and iterables are permitted for this action

Encountering an error while attempting to display a class in the HTML. <li> <ul> <li *ngFor="let refac of refactormodel" > -- word_to_rename: {{refac.word_to_rename}} -- renowned_word: {{refac.renowned_word}} ...

Navigating through Dynamic URL Parameters with RouterLink in an Angular Application

Within my Angular 2 application, there exists a tab section where users can choose from a collection of separate yet contextually connected components. By clicking on one of these links, the corresponding component is loaded based on the routerLink definit ...

Error: Uncaught TypeError - The function boss.SetBelongToClan is not defined

Currently, I am faced with an issue while working on a typescript and sequelize project within an express application. The problem arises when trying to create a type-safe interface for utilizing the associate function. Within my Instance interface, there ...

The process of sorting through an array of objects based on their specific types in TypeScript

I am working on a function that filters an array of objects based on their type property: export const retrieveLayoutChangeActions = (data: GetOperations['included']) => data.filter(d => d.type === 'layoutChangeAction') as Layou ...

Is there a way to verify the availability of an authenticated resource without triggering a pop-up for credentials in the browser?

I am facing the challenge of fetching data from a web service located on a different server without knowing if the user has an active session on that server. If the user does have a session, I want to retrieve the data automatically. However, if they do no ...

Why do users struggle to move between items displayed within the same component in Angular 16?

Lately, I've been immersed in developing a Single Page Application (SPA) using Angular 16, TypeScript, and The Movie Database (TMDB). During the implementation of a movies search feature, I encountered an unexpected issue. Within the app\servic ...

What is the best way to manage destroyed objects?

I've been working on a PIXI.js application and I'm faced with the challenge of managing resources to prevent memory leaks. To address this issue, I am utilizing the DisplayObject.destroy method. When a display object is destroyed, many of its in ...

Guide to transforming an embed/nested FormGroup into FormData

Presenting my Form Group: this.storeGroup = this.fb.group({ _user: [''], name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])], url_name: [''], desc: ['', Validators.compose([Valida ...