callback-this-type
Provide a Type for this in Callbacks if It's Part of Their API
Overview
When a library calls a user-provided callback with a specific this context, that context is part of the API. TypeScript allows you to type this as the first parameter of a function, even though it's not a real parameter. This documents and enforces the expected context.
When to Use This Skill
- Callbacks use
this - API provides
thiscontext - Typing event handlers
- Library sets
thisin callbacks - Documenting callback context
The Iron Rule
Type this as the first parameter when it's part of your callback API. This documents the expected context and enables autocompletion.
Example
// BAD: this is untyped
interface EventEmitter {
on(event: string, handler: (data: any) => void): void;
}
// User doesn't know what 'this' is:
emitter.on('click', function(data) {
this.something; // What properties does this have?
});
// GOOD: this is typed
interface EventEmitter {
on(
event: string,
handler: (this: EventContext, data: any) => void
): void;
}
interface EventContext {
target: Element;
timestamp: number;
preventDefault(): void;
}
// User now gets autocompletion for 'this'
emitter.on('click', function(data) {
this.target; // Autocomplete works!
this.timestamp; // Typed as number
});
Reference
- Effective TypeScript, 2nd Edition by Dan Vanderkam
- Item 69: Provide a Type for this in Callbacks if It's Part of Their API
More from marius-townhouse/effective-typescript-skills
exhaustiveness-checking
Use when handling tagged unions. Use when adding new cases to discriminated unions. Use when switch statements must cover all cases.
13code-gen-independent
Use when confused about types at runtime. Use when trying to use instanceof with interfaces. Use when type errors don't prevent JavaScript output.
12exclusive-or-properties
Use when exactly one of several properties should be present. Use when modeling mutually exclusive options. Use when building component props with alternative configurations. Use when designing API parameters that have variants.
11module-by-module-migration
Use when migrating large codebases. Use when converting JavaScript to TypeScript. Use when managing dependencies. Use when planning migration order. Use when teams are adopting TypeScript.
11editor-interrogation
Use when debugging type inference. Use when types behave unexpectedly. Use when learning unfamiliar code.
11precise-string-types
Use when working with string-typed properties. Use when string values have a limited set of options. Use when keyof could provide better type safety.
10