mcpField
C
callback-this-type

callback-this-type

github.com/marius-townhouseDevelopment644 installsUpdated 38w ago
Repository

About callback-this-type

A TypeScript skill for library authors and developers defining callback APIs. It explains how to declare a callback’s `this` context as a typed first parameter so the expected context is documented and available to tooling.

Key features

  1. 01Type callback `this` contexts
  2. 02Document callback API expectations
  3. 03Enable context-aware completion

Use cases

  1. 01Defining event-handler callback types
  2. 02Typing callbacks with library-set `this`
  3. 03Documenting callback context for API users

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/marius-townhouse/effective-typescript-skills --skill callback-this-type

After installing, type/callback-this-typein Claude Code to confirm it loaded.

Details

From the project README

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 this context
  • Typing event handlers
  • Library sets this in 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

Comments

Markdown supported