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'가 정의되지 않음

// 메서드를 분해할당
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

기본값: false

정적 메서드에 대해 바인딩되지 않은 메서드를 무시할지 여부. true로 설정하면 정적 메서드는 바인딩 없이 참조될 수 있습니다.

사용 방법

구성 파일 또는 명령줄 인터페이스를 통해 이 규칙을 활성화하려면 다음을 사용할 수 있습니다:

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

참고 자료