关于 callback-this-type
面向库作者和定义回调 API 的开发者的 TypeScript Skill。它说明如何将回调的 `this` 上下文声明为带类型的首个参数,从而记录预期上下文并支持工具提示。
主要功能
- 01为回调 `this` 上下文添加类型
- 02记录回调 API 预期
- 03提供上下文感知补全
适用场景
- 01定义事件处理器回调类型
- 02为库设置 `this` 的回调添加类型
- 03向 API 使用者说明回调上下文
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ marius-townhouse/ effective-typescript-skills --skill callback-this-type安装后在 Claude Code 中输入/callback-this-type确认已加载。
详细介绍
如果这是其 API 的一部分,就为回调中的 this 指定类型
概述
当库调用用户提供的回调,并为其指定特定的 this 上下文时,该上下文就是 API 的一部分。TypeScript 允许将 this 声明为函数的第一个参数,尽管它并不是真正的参数。这样可以记录并强制要求使用预期的上下文。
何时使用此技能
- 回调使用
this - API 提供
this上下文 - 为事件处理程序指定类型
- 库在回调中设置
this - 记录回调上下文
铁律
如果 this 是回调 API 的一部分,就将其指定为第一个参数的类型。这样可以记录预期的上下文,并启用自动补全。
示例
// 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
});
参考资料
- Dan Vanderkam 著,《Effective TypeScript》第 2 版
- 第 69 条:如果
this是 API 的一部分,就为回调中的this指定类型
评论
支持 Markdown