You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript super实现无法取值:Employee类不存在name属性报错问题

错误原因

  • 你在Person类中定义的#name是JS原生私有字段,带#前缀的私有字段是严格类私有属性,仅允许在声明该字段的类内部直接访问,子类、类外部均无法直接读取,所以你在子类Employee中直接访问this.name会报属性不存在的错误:你从来没有声明过公开的name属性,父类仅对外暴露了getName()方法读取私有姓名。
  • 你的代码还存在一处隐藏错误:giveRaise方法中await this.#storySalary漏了方法调用括号,正确写法是await this.#storySalary(),否则你await的是函数本身而非执行后的Promise对象。

修复方案

将Employee类中所有this.name替换为调用父类公开方法this.getName()即可,修正后的完整代码如下:

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.getName()}.`);
    }
    async #storySalary():Promise<void> {
        console.log(`Salary ¤ ${this.#salary} is stored for ${this.getName()}`);
    }
}

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

内容的提问来源于stack exchange,提问作者3gwebtrain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:06:02