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

我在Typescript网站上遇到了以下示例:

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可以访问generateReports(),因为它的类型也是会计部门。我已经运行了这段代码,它确实可以毫无问题地执行department.generateReports()

  • 当我在做
    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推断类型并将
    部门
    声明为
    会计部门

  • 抽象类是TypeScript特性,而不是JS,因此当TS被传输到JS时,
    Abstract
    关键字就被删除了。您将在编译时得到错误,就像大多数TypeScript特性一样,而不是在编译时。请参见此处的透明示例: