Skip to content
← Back to rules

typescript/unbound-method 正しさ

This rule is turned on by default when type-aware linting is enabled.
💭 This rule requires type information.

何をしますか

このルールは、バインドされていないメソッドが期待されるスコープで呼び出されることを強制します。

なぜ問題なのでしょうか

オブジェクトからメソッドを抽出して個別に呼び出すと、this コンテキストが失われます。これは、インスタンスのプロパティや他のメソッドにアクセスするために this に依存するメソッドの場合、実行時エラーまたは予期しない動作を引き起こす可能性があります。

このルールに対して不適切なコードの例:

ts
class MyClass {
  private value = 42;

  getValue() {
    return this.value;
  }

  processValue() {
    return this.value * 2;
  }
}

const instance = new MyClass();

// バインドされていないメソッド - 'this' コンテキストが失われる
const getValue = instance.getValue;
getValue(); // 実行時エラー: 'undefined' のプロパティ 'value' を読み取れません

// バインドされていないメソッドをコールバックとして渡す
[1, 2, 3].map(instance.processValue); // 'this' は undefined になる

// メソッドのデストラクチャリング
const { getValue: unboundGetValue } = instance;
unboundGetValue(); // 実行時エラー

このルールに対して適切なコードの例:

ts
class MyClass {
  private value = 42;

  getValue() {
    return this.value;
  }

  processValue() {
    return this.value * 2;
  }
}

const instance = new MyClass();

// インスタンス上でメソッドを呼び出す
const value = instance.getValue(); // 正しい

// メソッドをバインドしてコンテキストを保持する
const boundGetValue = instance.getValue.bind(instance);
boundGetValue(); // 正しい

// アロー関数を使ってコンテキストを保持する
[1, 2, 3].map(() => instance.processValue()); // 正しい

// クラス内でアロー関数を使用して自動的にバインドする
class MyClassWithArrow {
  private value = 42;

  getValue = () => {
    return this.value;
  };
}

const instance2 = new MyClassWithArrow();
const getValue = instance2.getValue; // 安全 - アロー関数は 'this' を保持する
getValue(); // 正しい

設定

このルールは、以下のプロパティを持つ設定オブジェクトを受け入れます。

ignoreStatic

type: boolean

default: false

静的メソッドについて、バインドされていない状態でも無視するかどうか。 true の場合、静的メソッドはバインドせずに参照してもよい。

使用方法

設定ファイルまたは CLI でこのルールを有効化するには、次のように使用できます:

json
{
  "rules": {
    "typescript/unbound-method": "error"
  }
}
bash
oxlint --type-aware --deny typescript/unbound-method

参照