首页 > 解决方案 > 类型脚本中的吸气剂不起作用!它总是抛出错误或返回未定义

问题描述

class Department {
    protected employees: string[] = [];

    constructor(private readonly id: string, public name: string) {
    }

    describe(this: Department) {
        console.log(`Department (${this.id}): ${this.name}`);
    }


    }
}

我创建了一个类,然后用另一个类扩展它

class AccountingDepartment extends Department{
    private readonly lastReport: string;

    get mostRecentReport() {
        if (this.lastReport) {
            return this.lastReport;
        }
        throw new Error('no report found.');
    }

    set mostRecentReport(value: string) {
        if (!value) {
            throw new Error('enter valid value')
        }
        this.addReport(value);
    }

    constructor(id: string, private reports: string[]) {
        super(id, 'Accounting');
        this.lastReport = reports[0];
    }



    addReport(text: string) {
        this.reports.push(text);
    }

    PrintReport() {
        console.log(this.reports);
    }
}

如上所述使用 getter 和 setter

const Accounting = new AccountingDepartment('D2', []);

Accounting.addReport('every thing is ok...');
Accounting.mostRecentReport = 'welecome';
Accounting.PrintReport();
console.log(Accounting.mostRecentReport);

我做错了什么我的代码在添加后返回错误(抛出新错误('未找到报告。');),!如果我评论它返回未定义的错误!

标签: typescript

解决方案


lastReport在构造函数中初始化后,您永远不会赋值
更新 addReport 方法如下

    ...
    private lastReport: string;
    ...
    addReport(text: string) {
        this.reports.push(text);
        this.lastReport = text;
    }
    ...

推荐阅读