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

Tailoring Aurelia for .cshtml integration

I stumbled upon an informative article detailing the integration of Razor partials (cshtml) with aurelia. Despite my efforts, I encountered difficulty in getting the code to execute properly and was informed by Rob Eisenberg's comment that Convention ...

Angular2/Typescript: Transforming a Javascript/Typescript Date into a C# DateTime string on the client side

Currently immersed in an Angular2/Typescript project, I am faced with the task of sending a date to a C# backend. Despite my extensive research, all I could uncover through Google searches was information on converting the date on the backend side. My la ...

What is the best way to dynamically add data to a JSON file?

image of JSON file Just a heads up: I'm looking to add data directly without the need to write it to a .json file, perhaps by using Angularfire2 database. user = { name: 'Arthur', age: 21 }; const options = {Headers, responseType: &apo ...

Is it possible to use TypeScript or Angular to disable or remove arrow key navigation from a PrimeNG Table programmatically?

Is there a way to programmatically prevent left and right arrow key navigation in a PrimeNG Table with cell editing, without the need to modify the Table component source code? You can check out an example here: Angular Primeng Tableedit Demo code. I mana ...

What is the proper way to supply a header parameter in Angular?

Encountering difficulties when trying to pass my header parameter in Angular. The error I'm receiving from my API states "Session Id is required" as shown below. Here is the endpoint: [HttpDelete("")] public IActionResult EndSession( ...

The Dilemma of using forRoot() in Angular 2/4+ Shared Modules

After uncovering the treasure that is forRoot() while delving deeper into Angular dependency injection (DI), I find myself pondering on the best practices for its usage. I came across this method when trying to enable a lazy loaded module to access a serv ...

Issue: Unable to link to 'FormGroup' because it is not recognized as a valid property of 'form'

app.module.ts import { BrowserModule } from '@angular/platform-browser'; import {CUSTOM_ELEMENTS_SCHEMA, NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import {AppRoutes} from './app.routin ...

Insert the object into a designated location within a multi-dimensional array

I've integrated a tree view into my Angular project and I'm looking to add an object to a specific position within an array. array const TREE_DATA: TreeNode[] = [{"name":"Demo","id":"demo_1","children ...

Mocking a common function in a shared service using Typescript and Jest

I have a service that is utilized with NestJS, although the issue at hand is not specific to NestJS. Nonetheless, testing in NestJS is involved, and I use it to create the service for testing purposes. This service is responsible for making multiple calls ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

Struggling to properly test the functionality of my NgForm call in Angular2+

I've been trying to test the login functionality by inputting username and password in an NgForm, but I keep encountering unsuccessful attempts. Is there a vital step that I may be overlooking? Currently, I'm facing this error message: Chrome 6 ...

Using Typescript and JSX to render a component that has been passed as an argument

I am seeking to create a function that will render a React component passed as an argument. I aim to accommodate both Component and StatelessComponent types with the following approach: function renderComponent(component: React.ComponentClass<any> | ...

Unique text: "Singleton React component"

A counter component has been implemented using a npm package available here. import * as React from 'react'; import { Theme, createStyles, withStyles, WithStyles } from '@material-ui/core'; import withRoot from '../../../withRoot&a ...

Issues with Next.js and Framer Motion

My component is throwing an error related to framer-motion. What could be causing this issue? Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function This error occurred during page generation. Any console logs will be ...

The Enum object in TypeScript has not been declared or defined

For my TypeScript application, I am utilizing WebPack to transpile and bundle the code. The final result is intended to be used in a pure JavaScript website. One of the components in my application is an enum defined as follows: export const enum ShapeTyp ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Filtering based on the boolean value of a checkbox in Angular

I'm struggling to implement a boolean filter for my search results, separating users with financial debt from those without. I need some guidance on how to achieve this. Data Filter @Pipe({ name: 'filter' }) export class FilterPipe implem ...

Obtain the combination of values within an array object

I am attempting to write the specifications for a function that can take records of any structure and convert the values into a discriminated union. For example: const getKeys = <T extends {key: string}>(items: T[]): T['key'] => { // ...

Preventing image flickering in SvelteKit: A guide

Upon the initial loading of a website, you may notice that the images tend to flicker or flash when transitioning between them. However, once these images are stored in the browser's cache, subsequent visits to the site will display the images seamles ...

Can you provide guidance on defining functions using standard syntax and incorporating children in React with TypeScript?

There are multiple ways to type it, such as using the interface React.FC<YourInterface> or explicitly declaring in an interface the type of children as JSX.Element or React.Node. Currently, my approach is: const MyComponent: React.FC<MyInterface& ...