关于 typescript-refactoring-patterns
typescript-refactoring-patterns 是面向 TypeScript 重构与类型安全实践的参考技能,提供类型收窄、变体建模和领域值验证模式。
主要功能
- 01类型守卫与判别联合
- 02常量断言与泛型约束
- 03用于领域验证的品牌类型
- 04用多态重构 switch 条件
- 05检查不安全类型相关代码异味
适用场景
- 01用类型守卫替代类型断言
- 02建模互斥状态
- 03验证领域专用字符串值
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ autohandai/ community-skills --skill typescript-refactoring-patterns安装后在 Claude Code 中输入/typescript-refactoring-patterns确认已加载。
详细介绍
TypeScript 重构模式
核心原则
- 类型收窄优于类型断言 - 使用类型守卫和可辨识联合,而不是
as类型转换 - 字面量使用 const 断言 - 使用
as const表示不可变的字面量类型 - 泛型约束 - 优先使用
extends约束,而不是any - 品牌类型 - 使用品牌类型进行特定领域的验证
重构模式
提取可辨识联合
看到多个布尔标志时,将其重构为可辨识联合:
// Before
interface User {
isAdmin: boolean;
isGuest: boolean;
permissions?: string[];
}
// After
type User =
| { role: 'admin'; permissions: string[] }
| { role: 'guest' }
| { role: 'member'; permissions: string[] };
用多态替换条件判断
看到基于类型的 switch 语句时,使用策略模式:
// Before
function process(item: Item) {
switch (item.type) {
case 'a': return processA(item);
case 'b': return processB(item);
}
}
// After
const processors: Record<ItemType, (item: Item) => Result> = {
a: processA,
b: processB,
};
const process = (item: Item) => processors[item.type](item);
提取类型守卫
收窄类型时,创建可复用的类型守卫:
function isNonNullable<T>(value: T): value is NonNullable<T> {
return value !== null && value !== undefined;
}
// Usage
const items = array.filter(isNonNullable);
使用品牌类型进行验证
使用品牌类型,避免原始类型偏执:
type UserId = string & { readonly brand: unique symbol };
type Email = string & { readonly brand: unique symbol };
function createUserId(id: string): UserId {
if (!isValidUuid(id)) throw new Error('Invalid user ID');
return id as UserId;
}
代码异味检测
留意以下模式并进行重构:
any类型(替换为unknown+ 类型守卫)- 非空断言
!(添加适当的检查) - 类型断言
as(使用类型守卫) - 滥用可选链
?.?.?.(重组数据) - 未经验证的索引签名
快速改进
- 在 tsconfig 中启用
strict: true - 使用
satisfies进行类型检查,避免类型扩大 - 优先使用
readonly数组和对象 - 对外部数据使用
unknown,并在边界处进行验证
评论
支持 Markdown