3
3

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 5 years have passed since last update.

【TypeScript】TypeScript の Getter と Setter

3
Posted at

TypeScriptのGetterとSetter

  • Getter/Setterを使うことで、カプセル化をしつつ、privateのプロパティを外部から取得/変更できます
    • カプセル化は、外部から内部のデータや処理を隠蔽する事です
  • Getter get メソッド名(引数:型)
  • Setter set メソッド名(引数:型)
//親クラス
class Department {

  protected employees: string[] = [];

  constructor(private readonly id: string, public name: string) {
  }
}
// AccountingDepartment サブクラス
class AccountingDepartment extends Department {
  private lastReport: string; 

  //Getterで、privateフィールドを外部から取得できるようにする
  get mostRecentReport() {
    if (this.lastReport) {  
      return this.lastReport; 
    }
    throw new Error('レポートが見つかりませんm(__)m');
  }

 //Setterで、privateフィールドを外部から変更できるようにする
  set mostRecentReport(value: string) {
    if (!value) { 
      throw new Error('正しい値を設定してください!');
    }
    this.addReport(value); //最新のレポートを追加
  }

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

  addReport(text: string) {
    this.reports.push(text);
    this.lastReport = text;
  }

}

const accounting = new AccountingDepartment('d2', []);
console.log(accounting.mostRecentReport); //レポートが見つかりません。

//レポートを追加
accounting.addReport('新しいレポートだよ');

//Getterで値を取得
console.log(accounting.mostRecentReport); //新しいレポートだよ
accounting.mostRecentReport = ''; //正しい値を設定してください!

//Setterで値を設定
accounting.mostRecentReport = '重要なレポート';
accounting.addReport('とても重要なレポート');  
console.log(accounting.mostRecentReport); //とても重要なレポート

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?