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 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);
我做错了什么我的代码在添加后返回错误(抛出新错误('未找到报告。');),!如果我评论它返回未定义的错误!
解决方案
lastReport
在构造函数中初始化后,您永远不会赋值
更新 addReport 方法如下
...
private lastReport: string;
...
addReport(text: string) {
this.reports.push(text);
this.lastReport = text;
}
...
推荐阅读
- google-cloud-storage - What is the difference between V4 and V2 Signing Process for Google Cloud Storage's Resources?
- excel - Excel 输入日期显示不正确
- python - 最小化功能
- json - json_decode 变量到电子邮件
- java - 基于子实体属性的 JPA 查询
- r - ggplotly:悬停时重命名工具提示
- angular - 如何通过分组对 ngx-datatable 应用排序
- php - php regex 获取特殊字符之间的关键字
- powerbi - DAX 问题计数记录与给定时间段的开始和结束日期和过滤器
- oracle - 我如何检查一年是否在 2000 年和当前年份之间?