ThisParameterType Extracts Callback Receivers

Read a function expected this type with ThisParameterType, strip it using OmitThisParameter, and bind a handler without losing parameters.

TypescriptData Integrity

Code

typescriptsnippet
24 lines
interface Counter {
  readonly label: string;
  count: number;
  increment(this: Counter, step: number): number;
}

type Receiver = ThisParameterType<Counter["increment"]>;
type PlainIncrement = OmitThisParameter<Counter["increment"]>;

const counter: Counter = {
  label: "clicks",
  count: 0,
  increment(this: Counter, step: number): number {
    this.count += step;
    return this.count;
  },
};

const receiver: Receiver = counter;
const detached: PlainIncrement = counter.increment.bind(counter);

console.log(receiver.label, receiver.increment(2));
console.log("detached result", detached(3));
console.log("receiver has count", "count" in receiver);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

clicks 2
detached result 5
receiver has count true

Caveats

  • Nothing to add to the project before running it.

Using it

Each run prints the 2 labeled blocks detached result, receiver has count in source order.

Output is labeled for readability — expect lines prefixed with detached result, receiver has count.

Key statements

this.count += step;

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library.