【问题标题】:Typescript `super` implementation not providing the valueTypescript`super`实现不提供值
【发布时间】:2021-11-01 04:22:55
【问题描述】:

我正在尝试从extended 类打印name。但收到错误消息: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

【问题讨论】:

    标签: typescript typescript-class


    【解决方案1】:

    #name:string; 表示name 是私有属性,不能扩展私有变量。

    您可能正在寻找的是protected name: string

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

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 2011-08-18
      • 1970-01-01
      • 2010-11-23
      • 2021-07-16
      相关资源
      最近更新 更多