This Parameter Typing For Callbacks

Type methods with an explicit this parameter so detached calls fail compilation, and bind() restores the context instead of silently losing state.

TypescriptData Integrity

Code

typescriptsnippet
25 lines
class VoteCounter {
  count = 0;

  // this 参数:把方法与实例类型绑死,方法被拆下来调用直接编译报错
  increment(this: VoteCounter, by = 1): void {
    this.count += by;
  }
}

const counter = new VoteCounter();
counter.increment();
counter.increment(4);
console.log('bound:', counter.count);

const detached = counter.increment;
try {
  // @ts-expect-error: this 上下文缺失(TS2684)
  detached();
} catch (error) {
  console.log('detached fails with TypeError:', error instanceof TypeError);
}

const rebinded = counter.increment.bind(counter);
rebinded(2);
console.log('rebinded:', counter.count);

How it works

The code’s whole job belongs to the class VoteCounter.

Module-level bindings hold the data — counter, detached, rebinded — with no function scope in between.

Using it

Running the file prints labeled results such as bound:, detached fails with TypeError:, rebinded: — each operation’s effect is visible in the output.

Key statements

this.count += by;

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `counter`, `detached`, `rebinded`.