🔷 TypeScript の static
(静的メソッド・プロパティ)
✅ 静的メソッド(static method)
- インスタンス化せずに呼び出せる
- クラス名を使って直接アクセス
✅ 静的プロパティ(static property)
- すべてのインスタンスで共有される
- 定数や共通値の定義に便利
🧪 使用例
class MathUtil {
static PI: number = 3.14159;
static square(x: number): number {
return x * x;
}
}
console.log(MathUtil.PI); // 3.14159
console.log(MathUtil.square(5)); // 25
// const util = new MathUtil();
// console.log(util.square(5)); // ❌ エラー:インスタンスからは呼べない
🛠 特徴と使いどころ
機能 | 使いどころ |
static プロパティ | 定数や共有設定 |
static メソッド | ユーティリティ関数やツール系の処理 |
❗ 注意点
static
メンバ内では this
はクラス自身を指す
- インスタンスのメンバ(非
static
)にはアクセス不可
class Demo {
static sayHello(): void {
// console.log(this.name); // 🔴 インスタンスの name は使えない
console.log("Hello!");
}
name = "Kenji";
}
✅ まとめ
要素 | アクセス方法 | 備考 |
static プロパティ |
クラス名.プロパティ名 |
共有定数や設定などに利用 |
static メソッド |
クラス名.メソッド名() |
ユーティリティ・計算処理などに最適 |
非 static |
インスタンス.メソッド名() |
インスタンス固有の処理に使用 |