Typescript 类型脚本中的getter不工作!!!它总是抛出错误或返回未定义
我将一个类划分为框架,然后用另一个扩展它Typescript 类型脚本中的getter不工作!!!它总是抛出错误或返回未定义,typescript,Typescript,我将一个类划分为框架,然后用另一个扩展它 class Department { protected employees: string[] = []; constructor(private readonly id: string, public name: string) { } describe(this: Department) { console.log(`Department (${this.id}): ${this.name}`);
class Department {
protected employees: string[] = [];
constructor(private readonly id: string, public name: string) {
}
describe(this: Department) {
console.log(`Department (${this.id}): ${this.name}`);
}
}
}
如上所述使用getter和setter
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);
}
}
我做错了什么
我的代码返回错误抛出新错误“未找到报告”;添加后!!
如果我对错误进行注释,它将返回undefined 在构造函数中初始化lastReport值后,永远不会为其赋值
更新addReport方法,如下所示
const Accounting = new AccountingDepartment('D2', []);
Accounting.addReport('every thing is ok...');
Accounting.mostRecentReport = 'welecome';
Accounting.PrintReport();
console.log(Accounting.mostRecentReport);
尝试删除lastReport的readonly,并在AccountingDepartment的构造函数中添加空数组检查此。lastReport=reports[0]//空数组我尝试了这两种方法,如果使用空数组,编译时会出错。
...
private lastReport: string;
...
addReport(text: string) {
this.reports.push(text);
this.lastReport = text;
}
...