Skip to content
← Back to rules

typescript/unbound-method Correctness

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

What it does

This rule enforces that unbound methods are called with their intended scope.

Why is this bad?

When you extract a method from an object and call it separately, the this context is lost. This can lead to runtime errors or unexpected behavior, especially when methods rely on this to access instance properties or other methods.

Examples

Here are examples of incorrect code for this rule:

ts
class MyClass {
  private value = 42;

  getValue() {
    return this.value;
  }

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

const instance = new MyClass();

// Unbound method - loses 'this' context
const getValue = instance.getValue;
getValue(); // Runtime error: Cannot read property 'value' of undefined

// Passing unbound method as callback
[1, 2, 3].map(instance.processValue); // 'this' will be undefined

// Destructuring method
const { getValue: unboundGetValue } = instance;
unboundGetValue(); // Runtime error

Here are examples of correct code for this rule:

ts
class MyClass {
  private value = 42;

  getValue() {
    return this.value;
  }

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

const instance = new MyClass();

// Call the method on the instance
const value = instance.getValue(); // Correct

// Bind the method to preserve context
const boundGetValue = instance.getValue.bind(instance);
boundGetValue(); // Correct

// Use an arrow function to preserve context
[1, 2, 3].map(() => instance.processValue()); // Correct

// Use an arrow function in class to auto-bind
class MyClassWithArrow {
  private value = 42;

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

const instance2 = new MyClassWithArrow();
const getValue = instance2.getValue; // Safe - arrow function preserves 'this'
getValue(); // Correct

Configuration

This rule accepts a configuration object with the following properties:

ignoreStatic

type: boolean

default: false

Whether to ignore static unbound methods. When true, static methods can be referenced without binding.

How to use

To enable this rule using the config file or in the CLI, you can use:

json
{
  "options": {
    "typeAware": true
  },
  "rules": {
    "typescript/unbound-method": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  options: { typeAware: true },
  rules: {
    "typescript/unbound-method": "error",
  },
});
bash
oxlint --type-aware --deny typescript/unbound-method

Version

This rule was added in v1.12.0.

References