Typescript 扩展抽象类的类的执行方法
我在Typescript网站上遇到了以下示例:Typescript 扩展抽象类的类的执行方法,typescript,oop,Typescript,Oop,我在Typescript网站上遇到了以下示例: abstract class Department { constructor(public name: string) { } printName(): void { console.log("Department name: " + this.name); } abstract printMeeting(): void; // must be implemented in deriv
abstract class Department {
constructor(public name: string) {
}
printName(): void {
console.log("Department name: " + this.name);
}
abstract printMeeting(): void; // must be implemented in derived classes
}
class AccountingDepartment extends Department {
constructor() {
super("Accounting and Auditing"); // constructors in derived classes must call super()
}
printMeeting(): void {
console.log("The Accounting Department meets each Monday at 10am.");
}
generateReports(): void {
console.log("Generating accounting reports...");
}
}
let department: Department; // ok to create a reference to an abstract type
department = new Department(); // error: cannot create an instance of an abstract class
department = new AccountingDepartment(); // ok to create and assign a non-abstract subclass
department.printName();
department.printMeeting();
**department.generateReports();** // error: method doesn't exist on declared abstract type???
关于这一点,我有两个问题:
department=newdepartment()时代码>虽然创建抽象类的实例是一个错误,但它并没有给我一个运行时错误。为什么会这样?不创建抽象类的实例是我的责任吗
部门
被声明为一个部门
,这意味着即使它可能是一个会计部门
,也不能保证它是。想想看:
let department: Department;
// ...
department = departmentName === 'accounting'
? new AccountingDepartment()
: new CustomerCareDepartment();
// ...
department.generateReports(); // You really can't know if it's available
如果您只是键入让department=newaccountingdepartment()代码>本来可以,因为TS推断类型并将部门
声明为会计部门
Abstract
关键字就被删除了。您将在编译时得到错误,就像大多数TypeScript特性一样,而不是在编译时。请参见此处的透明示例: