typescript-refactor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript Refactor Best Practices

TypeScript重构最佳实践

Comprehensive TypeScript refactoring and modernization guide designed for AI agents and LLMs. Contains 43 rules across 8 categories, prioritized by impact to guide automated refactoring, code review, and code generation.
这是一份为AI Agent和大语言模型(LLM)设计的全面TypeScript重构与现代化指南。指南包含8个类别共43条规则,按影响优先级排序,可用于指导自动化重构、代码审查和代码生成。

When to Apply

适用场景

Reference these guidelines when:
  • Refactoring TypeScript code for type safety and maintainability
  • Designing type architectures (discriminated unions, branded types, generics)
  • Narrowing types to eliminate unsafe
    as
    casts
  • Adopting modern TypeScript 4.x-5.x features (
    satisfies
    ,
    using
    , const type parameters)
  • Optimizing compiler performance in large codebases
  • Implementing type-safe error handling patterns
  • Reviewing code for TypeScript quirks and pitfalls
在以下场景中可参考本指南:
  • 重构TypeScript代码以提升类型安全性与可维护性
  • 设计类型架构(discriminated unions、branded types、generics)
  • 通过类型收窄消除不安全的
    as
    类型断言
  • 采用现代TypeScript 4.x-5.x特性(
    satisfies
    using
    、const type parameters)
  • 在大型代码库中优化编译器性能
  • 实现类型安全的错误处理模式
  • 审查代码以规避TypeScript的特性陷阱

Rule Categories by Priority

按优先级排序的规则类别

PriorityCategoryImpactPrefix
1Type ArchitectureCRITICAL
arch-
2Type Narrowing & GuardsCRITICAL
narrow-
3Modern TypeScriptHIGH
modern-
4Generic PatternsHIGH
generic-
5Compiler PerformanceMEDIUM-HIGH
compile-
6Error SafetyMEDIUM
error-
7Runtime PatternsMEDIUM
perf-
8Quirks & PitfallsLOW-MEDIUM
quirk-
优先级类别影响程度前缀
1Type Architecture关键
arch-
2Type Narrowing & Guards关键
narrow-
3Modern TypeScript
modern-
4Generic Patterns
generic-
5Compiler Performance中高
compile-
6Error Safety
error-
7Runtime Patterns
perf-
8Quirks & Pitfalls中低
quirk-

Quick Reference

快速参考

1. Type Architecture (CRITICAL)

1. Type Architecture(关键)

  • arch-discriminated-unions
    — Use discriminated unions over string enums for exhaustive pattern matching
  • arch-branded-types
    — Use branded types for domain identifiers to prevent value mix-ups
  • arch-satisfies-over-annotation
    — Use
    satisfies
    for config objects to preserve literal types
  • arch-interfaces-over-intersections
    — Extend interfaces instead of intersecting types for better error messages
  • arch-const-assertion
    — Use
    as const
    for immutable literal inference
  • arch-readonly-by-default
    — Default to readonly types for function parameters and return values
  • arch-avoid-partial-abuse
    — Avoid
    Partial<T>
    abuse for builder patterns
  • arch-discriminated-unions
    — 优先使用discriminated unions而非字符串枚举,以实现穷尽模式匹配
  • arch-branded-types
    — 使用branded types处理领域标识符,避免值混淆
  • arch-satisfies-over-annotation
    — 对配置对象使用
    satisfies
    ,以保留字面量类型
  • arch-interfaces-over-intersections
    — 优先扩展接口而非交叉类型,以获得更清晰的错误提示
  • arch-const-assertion
    — 使用
    as const
    实现不可变字面量类型推断
  • arch-readonly-by-default
    — 函数参数与返回值默认使用只读类型
  • arch-avoid-partial-abuse
    — 避免滥用
    Partial<T>
    实现构建器模式

2. Type Narrowing & Guards (CRITICAL)

2. Type Narrowing & Guards(关键)

  • narrow-custom-type-guards
    — Write custom type guards instead of type assertions
  • narrow-assertion-functions
    — Use assertion functions for precondition checks
  • narrow-exhaustive-switch
    — Enforce exhaustive switch with
    never
  • narrow-in-operator
    — Narrow with the
    in
    operator for interface unions
  • narrow-eliminate-as-casts
    — Eliminate
    as
    casts with proper narrowing chains
  • narrow-typeof-chains
    — Use
    typeof
    narrowing before property access
  • narrow-custom-type-guards
    — 编写自定义类型守卫而非使用类型断言
  • narrow-assertion-functions
    — 使用断言函数进行前置条件检查
  • narrow-exhaustive-switch
    — 用
    never
    类型强制实现穷尽switch语句
  • narrow-in-operator
    — 对接口联合类型使用
    in
    操作符进行类型收窄
  • narrow-eliminate-as-casts
    — 通过合理的类型收窄链消除
    as
    类型断言
  • narrow-typeof-chains
    — 在访问属性前使用
    typeof
    进行类型收窄

3. Modern TypeScript (HIGH)

3. Modern TypeScript(高)

  • modern-using-keyword
    — Use the
    using
    keyword for resource cleanup
  • modern-const-type-parameters
    — Use const type parameters for literal inference
  • modern-template-literal-types
    — Use template literal types for string patterns
  • modern-noinfer-utility
    — Use
    NoInfer
    to control type parameter inference
  • modern-accessor-keyword
    — Use
    accessor
    for auto-generated getters and setters
  • modern-verbatim-module-syntax
    — Enable
    verbatimModuleSyntax
    for explicit import types
  • modern-using-keyword
    — 使用
    using
    关键字进行资源清理
  • modern-const-type-parameters
    — 使用const类型参数实现字面量类型推断
  • modern-template-literal-types
    — 使用模板字面量类型处理字符串模式
  • modern-noinfer-utility
    — 使用
    NoInfer
    控制类型参数推断
  • modern-accessor-keyword
    — 使用
    accessor
    关键字自动生成getter和setter
  • modern-verbatim-module-syntax
    — 启用
    verbatimModuleSyntax
    以实现显式导入类型

4. Generic Patterns (HIGH)

4. Generic Patterns(高)

  • generic-infer-over-annotate
    — Let TypeScript infer instead of explicit annotation
  • generic-constrain-dont-overconstrain
    — Constrain generics minimally
  • generic-avoid-distributive-surprises
    — Control distributive conditional types
  • generic-mapped-type-utilities
    — Build custom mapped types for repeated transformations
  • generic-return-type-inference
    — Preserve return type inference in generic functions
  • generic-infer-over-annotate
    — 优先让TypeScript自动推断类型而非显式注解
  • generic-constrain-dont-overconstrain
    — 最小化约束泛型类型
  • generic-avoid-distributive-surprises
    — 控制分布式条件类型的行为
  • generic-mapped-type-utilities
    — 构建自定义映射类型以实现重复转换逻辑
  • generic-return-type-inference
    — 在泛型函数中保留返回类型推断

5. Compiler Performance (MEDIUM-HIGH)

5. Compiler Performance(中高)

  • compile-explicit-return-types
    — Add explicit return types to exported functions
  • compile-avoid-deep-recursion
    — Avoid deeply recursive type definitions
  • compile-project-references
    — Use project references for monorepo builds
  • compile-base-types-over-unions
    — Use base types instead of large union types
  • compile-explicit-return-types
    — 为导出函数添加显式返回类型
  • compile-avoid-deep-recursion
    — 避免使用深度递归的类型定义
  • compile-project-references
    — 在 monorepo 构建中使用项目引用
  • compile-base-types-over-unions
    — 优先使用基础类型而非大型联合类型

6. Error Safety (MEDIUM)

6. Error Safety(中)

  • error-result-type
    — Use Result types instead of thrown exceptions
  • error-exhaustive-error-handling
    — Use exhaustive checks for typed error variants
  • error-typed-catch
    — Type catch clause variables as
    unknown
  • error-never-for-unreachable
    — Use
    never
    to mark unreachable code paths
  • error-discriminated-error-unions
    — Model domain errors as discriminated unions
  • error-result-type
    — 使用Result类型替代抛出异常
  • error-exhaustive-error-handling
    — 对类型化错误变体进行穷尽检查
  • error-typed-catch
    — 将catch子句变量类型标注为
    unknown
  • error-never-for-unreachable
    — 使用
    never
    类型标记不可达代码路径
  • error-discriminated-error-unions
    — 将领域错误建模为discriminated unions

7. Runtime Patterns (MEDIUM)

7. Runtime Patterns(中)

  • perf-union-literals-over-enums
    — Use union literals instead of enums
  • perf-avoid-delete-operator
    — Avoid the
    delete
    operator on objects
  • perf-object-freeze-const
    — Use
    Object.freeze
    with
    as const
    for true immutability
  • perf-object-keys-narrowing
    — Avoid
    Object.keys
    type widening
  • perf-map-set-over-object
    — Use
    Map
    and
    Set
    over plain objects for dynamic collections
  • perf-union-literals-over-enums
    — 使用联合字面量而非枚举
  • perf-avoid-delete-operator
    — 避免在对象上使用
    delete
    操作符
  • perf-object-freeze-const
    — 结合
    Object.freeze
    as const
    实现真正的不可变性
  • perf-object-keys-narrowing
    — 避免
    Object.keys
    的类型拓宽问题
  • perf-map-set-over-object
    — 对动态集合优先使用
    Map
    Set
    而非普通对象

8. Quirks & Pitfalls (LOW-MEDIUM)

8. Quirks & Pitfalls(中低)

  • quirk-excess-property-checks
    — Understand excess property checks on object literals
  • quirk-empty-object-type
    — Avoid the
    {}
    type — it means non-nullish
  • quirk-type-widening-let
    — Prevent type widening with
    let
    declarations
  • quirk-variance-annotations
    — Use variance annotations for generic interfaces
  • quirk-structural-typing-escapes
    — Guard against structural typing escape hatches
  • quirk-excess-property-checks
    — 理解对象字面量的多余属性检查机制
  • quirk-empty-object-type
    — 避免使用
    {}
    类型——它表示非空值类型
  • quirk-type-widening-let
    — 避免
    let
    声明导致的类型拓宽
  • quirk-variance-annotations
    — 为泛型接口使用方差注解
  • quirk-structural-typing-escapes
    — 防范结构类型的漏洞

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions — Category structure and impact levels
  • Rule template — Template for adding new rules
阅读单个参考文件以获取详细说明和代码示例:
  • 章节定义 — 类别结构与影响级别说明
  • 规则模板 — 添加新规则的模板

Reference Files

参考文件

FileDescription
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
references/_sections.md类别定义与排序规则
assets/templates/_template.md新规则模板
metadata.json版本与参考信息