类型脚本中的获取器不起作用!!!它总是抛出错误或返回undefined

问题描述 投票:0回答:1
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
1个回答
0
投票

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

    ...
    private lastReport: string;
    ...
    addReport(text: string) {
        this.reports.push(text);
        this.lastReport = text;
    }
    ...
© www.soinside.com 2019 - 2024. All rights reserved.