11
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【TypeScript】TypeScript の abstract メソッド/クラス

Posted at

#TypeScript の abstractメソッド

  • 親クラスのメソッドをサブクラスでオーバーライドするように強制したい場合、abstractメソッド使います
  • abstractメソッドでは、具体的なメソッドの処理を書かず、戻り値のみを設定します
  abstract describe(this: Department): void; //{};を削除、戻り値を設定

##ポイント

  • abstractメソッドは、abstractクラスからしか使用できません
  • abstract クラスは、インスタンス化できません
  • サブクラスで、必ず親クラスのabstractメソッドを実装します
//親クラス

abstract class Department {
  static fiscalYear = 2021;
  protected employees: string[] = [];

  static createEmployee(name: string) {
    return { name: name };
  }

  constructor(protected readonly id: string, public name: string) {
    console.log(Department.fiscalYear);
  }

  abstract describe(this: Department): void;

}
//サブクラス1

class ITDepartment extends Department {
  admins: string[];
  constructor(id: string, admins: string[]) {
    super(id, 'IT');
    this.admins = admins;
  }

  //親クラスのabstractメソッドをサブクラスで実装する必要がある
  describe() { 
    console.log('IT部署 - ID: ' + this.id);
  }
}

//サブクラス2

class AccountingDepartment extends Department {
  private lastReport: string;

  constructor(id: string, private reports: string[]) {
    super(id, 'Accounting');
    this.lastReport = reports[0];
  }

  //親クラスのabstractメソッドをサブクラスで実装する必要がある
  describe() {
    console.log('会計部署 - ID: ' + this.id);
  }
}
11
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?