Home > front end >  Typescript `super` implementation not providing the value
Typescript `super` implementation not providing the value

Time:11-02

I am trying to print the name from extended class. But getting an error as : Property 'name' does not exist on type 'Employee'.

class Person {
    #name:string;
    getName(){
        return this.#name;
    }
    constructor(name:string){
        this.#name = name;
    }
}

class Employee extends Person {

    #salary:number;
    constructor(name:string, salary:number = 0){
        super(name);
        this.#salary = salary;
    }
    async giveRaise(raise:number):Promise<void> {
        this.#salary  = raise;
        await this.#storySalary;
    }

    pay():void {
        console.log(${this.#salary} is paid to ${this.name}.`);
    }
    async #storySalary():Promise<void> {
        console.log(`Salary ¤ ${this.#salary} is stored for ${this.name}`);
    }
}

const NewEmployee = new Employee('Sha', 300);
console.log(NewEmployee.getName(), NewEmployee.pay())

Live Demo

CodePudding user response:

#name:string; means name is a private property, you cannot extend private variables.

What you might be looking for is protected name: string

class Person {
    protected name:string;
    getName(){
        return this.name;
    }
    constructor(name:string){
        this.name = name;
    }
}
  • Related