LoginSignup
12
5

More than 3 years have passed since last update.

【TypeScript】TypeScript の static プロパティ/メソッド

Posted at

TypeScript の static プロパティ/メソッド

  • static プロパティ/メソッドを使うと、newしてクラスのインスタンスを作らずとも、クラスのプロパティ、メソッドを使えます
    • クラスに utilityメソッド(複数箇所で使う便利ツール) を用意して、外部で使う場合などに便利です(^o^)
  • staticプロパティは、インスタンスからアクセスできないので、コンストラクタや、static以外のメソッドから、アクセスできないです
    • 例えば Mathクラスのメソッドも、Mathクラスをnewしなくても使えますね〜
//staticメソッドの例
Math.pow();

staticプロパティを作成する

  • staticプロパティには、this.(プロパティ) のようにアクセスできません
    • thisはクラスを元に作られたインスタンスを指すからです
  • クラス名を指定したら、staticプロパティにアクセス可能になります
 class Department {
  static fiscalYear = 2021; //staticプロパティ
  protected employees: string[] = [];

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

staticメソッドを作成する

  • メソッド名にstaticをつけると、newしなくても、外部で利用可能になります
 class Department {
  static fiscalYear = 2021; //staticプロパティ
  protected employees: string[] = [];

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

  static createEmployee(name: string) { //staticメソッド
    return { name: name };
  }
}


const employee1 = Department.createEmployee('NEKO'); //newしなくてOK
console.log(employee1, Department.fiscalYear);

12
5
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
12
5