Gandalf
Gandalf

Reputation: 3257

How to properly override a method in typescript?

Why is this.fullName empty in 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();

How should I fix this?

Upvotes: 6

Views: 6709

Answers (2)

y2bd
y2bd

Reputation: 6466

super() is always the first thing called when constructing a derived class like your Man. This includes being before any variable initialization you do, such as protected fullName = ''. Therefore, while your Man.makeSir is being called and setting fullName to a good value, right afterwards your empty string assignment kicks in and clears its value.

One way to avoid this late overwrite is to not set an initial value for fullName:

// give it a type because we don't give it an initial value
// use `!` syntax to hint to TypeScript that this will be initialized during the constructor
// even though TS cannot figure that out itself
protected fullName!: string;

Now since you never set fullName to an "initial" value, you never overwrite the work done by the super() call.

Upvotes: 7

Arfat Binkileb
Arfat Binkileb

Reputation: 671

class Person  {
    
protected name: String ="";
    
    constructor(name: string){
        this.makeSir(name);
    }
    
    makeSir(name: string){
        this.name="sir"+name ;
    }
    
    test(){
        console.log("PERSON");
    }
}

class Man extends Person {
    public name: string ="";
    
    constructor(name:string){
        super(name);
        this.makeSir(name);
    }
    
    makeSir(name:string){
        this.name="####"+name;
    }
    
    test(){
        console.log("Man ")
    }
    show(){
        console.log("#####"+this.name);
    }
}

const n = new Man("Man ")
n.show();
n.test();


const m = new Person("Person");
m.test();

Your are only calling super in constructor, which in tern calls super constructor only.

If you see test is overridden properly

Output:

#########Man 
Man 
PERSON

Upvotes: 2

Related Questions