mcpField
T
typescript-refactoring-patterns

typescript-refactoring-patterns

github.com/autohandai开发1159 次安装15 周前更新
代码仓库

关于 typescript-refactoring-patterns

typescript-refactoring-patterns 是面向 TypeScript 重构与类型安全实践的参考技能,提供类型收窄、变体建模和领域值验证模式。

主要功能

  1. 01类型守卫与判别联合
  2. 02常量断言与泛型约束
  3. 03用于领域验证的品牌类型
  4. 04用多态重构 switch 条件
  5. 05检查不安全类型相关代码异味

适用场景

  1. 01用类型守卫替代类型断言
  2. 02建模互斥状态
  3. 03验证领域专用字符串值

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/autohandai/community-skills --skill typescript-refactoring-patterns

安装后在 Claude Code 中输入/typescript-refactoring-patterns确认已加载。

详细介绍

TypeScript 重构模式

核心原则

  1. 类型收窄优于类型断言 - 使用类型守卫和可辨识联合,而不是 as 类型转换
  2. 字面量使用 const 断言 - 使用 as const 表示不可变的字面量类型
  3. 泛型约束 - 优先使用 extends 约束,而不是 any
  4. 品牌类型 - 使用品牌类型进行特定领域的验证

重构模式

提取可辨识联合

看到多个布尔标志时,将其重构为可辨识联合:

// 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(使用类型守卫)
  • 滥用可选链 ?.?.?.(重组数据)
  • 未经验证的索引签名

快速改进

  1. 在 tsconfig 中启用 strict: true
  2. 使用 satisfies 进行类型检查,避免类型扩大
  3. 优先使用 readonly 数组和对象
  4. 对外部数据使用 unknown,并在边界处进行验证

评论

支持 Markdown