typescript-refactor
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript 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 casts
as - Adopting modern TypeScript 4.x-5.x features (,
satisfies, const type parameters)using - 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、const type parameters)using - 在大型代码库中优化编译器性能
- 实现类型安全的错误处理模式
- 审查代码以规避TypeScript的特性陷阱
Rule Categories by Priority
按优先级排序的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Type Architecture | CRITICAL | |
| 2 | Type Narrowing & Guards | CRITICAL | |
| 3 | Modern TypeScript | HIGH | |
| 4 | Generic Patterns | HIGH | |
| 5 | Compiler Performance | MEDIUM-HIGH | |
| 6 | Error Safety | MEDIUM | |
| 7 | Runtime Patterns | MEDIUM | |
| 8 | Quirks & Pitfalls | LOW-MEDIUM | |
| 优先级 | 类别 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | Type Architecture | 关键 | |
| 2 | Type Narrowing & Guards | 关键 | |
| 3 | Modern TypeScript | 高 | |
| 4 | Generic Patterns | 高 | |
| 5 | Compiler Performance | 中高 | |
| 6 | Error Safety | 中 | |
| 7 | Runtime Patterns | 中 | |
| 8 | Quirks & Pitfalls | 中低 | |
Quick Reference
快速参考
1. Type Architecture (CRITICAL)
1. Type Architecture(关键)
- — Use discriminated unions over string enums for exhaustive pattern matching
arch-discriminated-unions - — Use branded types for domain identifiers to prevent value mix-ups
arch-branded-types - — Use
arch-satisfies-over-annotationfor config objects to preserve literal typessatisfies - — Extend interfaces instead of intersecting types for better error messages
arch-interfaces-over-intersections - — Use
arch-const-assertionfor immutable literal inferenceas const - — Default to readonly types for function parameters and return values
arch-readonly-by-default - — Avoid
arch-avoid-partial-abuseabuse for builder patternsPartial<T>
- — 优先使用discriminated unions而非字符串枚举,以实现穷尽模式匹配
arch-discriminated-unions - — 使用branded types处理领域标识符,避免值混淆
arch-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(关键)
- — Write custom type guards instead of type assertions
narrow-custom-type-guards - — Use assertion functions for precondition checks
narrow-assertion-functions - — Enforce exhaustive switch with
narrow-exhaustive-switchnever - — Narrow with the
narrow-in-operatoroperator for interface unionsin - — Eliminate
narrow-eliminate-as-castscasts with proper narrowing chainsas - — Use
narrow-typeof-chainsnarrowing before property accesstypeof
- — 编写自定义类型守卫而非使用类型断言
narrow-custom-type-guards - — 使用断言函数进行前置条件检查
narrow-assertion-functions - — 用
narrow-exhaustive-switch类型强制实现穷尽switch语句never - — 对接口联合类型使用
narrow-in-operator操作符进行类型收窄in - — 通过合理的类型收窄链消除
narrow-eliminate-as-casts类型断言as - — 在访问属性前使用
narrow-typeof-chains进行类型收窄typeof
3. Modern TypeScript (HIGH)
3. Modern TypeScript(高)
- — Use the
modern-using-keywordkeyword for resource cleanupusing - — Use const type parameters for literal inference
modern-const-type-parameters - — Use template literal types for string patterns
modern-template-literal-types - — Use
modern-noinfer-utilityto control type parameter inferenceNoInfer - — Use
modern-accessor-keywordfor auto-generated getters and settersaccessor - — Enable
modern-verbatim-module-syntaxfor explicit import typesverbatimModuleSyntax
- — 使用
modern-using-keyword关键字进行资源清理using - — 使用const类型参数实现字面量类型推断
modern-const-type-parameters - — 使用模板字面量类型处理字符串模式
modern-template-literal-types - — 使用
modern-noinfer-utility控制类型参数推断NoInfer - — 使用
modern-accessor-keyword关键字自动生成getter和setteraccessor - — 启用
modern-verbatim-module-syntax以实现显式导入类型verbatimModuleSyntax
4. Generic Patterns (HIGH)
4. Generic Patterns(高)
- — Let TypeScript infer instead of explicit annotation
generic-infer-over-annotate - — Constrain generics minimally
generic-constrain-dont-overconstrain - — Control distributive conditional types
generic-avoid-distributive-surprises - — Build custom mapped types for repeated transformations
generic-mapped-type-utilities - — Preserve return type inference in generic functions
generic-return-type-inference
- — 优先让TypeScript自动推断类型而非显式注解
generic-infer-over-annotate - — 最小化约束泛型类型
generic-constrain-dont-overconstrain - — 控制分布式条件类型的行为
generic-avoid-distributive-surprises - — 构建自定义映射类型以实现重复转换逻辑
generic-mapped-type-utilities - — 在泛型函数中保留返回类型推断
generic-return-type-inference
5. Compiler Performance (MEDIUM-HIGH)
5. Compiler Performance(中高)
- — Add explicit return types to exported functions
compile-explicit-return-types - — Avoid deeply recursive type definitions
compile-avoid-deep-recursion - — Use project references for monorepo builds
compile-project-references - — Use base types instead of large union types
compile-base-types-over-unions
- — 为导出函数添加显式返回类型
compile-explicit-return-types - — 避免使用深度递归的类型定义
compile-avoid-deep-recursion - — 在 monorepo 构建中使用项目引用
compile-project-references - — 优先使用基础类型而非大型联合类型
compile-base-types-over-unions
6. Error Safety (MEDIUM)
6. Error Safety(中)
- — Use Result types instead of thrown exceptions
error-result-type - — Use exhaustive checks for typed error variants
error-exhaustive-error-handling - — Type catch clause variables as
error-typed-catchunknown - — Use
error-never-for-unreachableto mark unreachable code pathsnever - — Model domain errors as discriminated unions
error-discriminated-error-unions
- — 使用Result类型替代抛出异常
error-result-type - — 对类型化错误变体进行穷尽检查
error-exhaustive-error-handling - — 将catch子句变量类型标注为
error-typed-catchunknown - — 使用
error-never-for-unreachable类型标记不可达代码路径never - — 将领域错误建模为discriminated unions
error-discriminated-error-unions
7. Runtime Patterns (MEDIUM)
7. Runtime Patterns(中)
- — Use union literals instead of enums
perf-union-literals-over-enums - — Avoid the
perf-avoid-delete-operatoroperator on objectsdelete - — Use
perf-object-freeze-constwithObject.freezefor true immutabilityas const - — Avoid
perf-object-keys-narrowingtype wideningObject.keys - — Use
perf-map-set-over-objectandMapover plain objects for dynamic collectionsSet
- — 使用联合字面量而非枚举
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(中低)
- — Understand excess property checks on object literals
quirk-excess-property-checks - — Avoid the
quirk-empty-object-typetype — it means non-nullish{} - — Prevent type widening with
quirk-type-widening-letdeclarationslet - — Use variance annotations for generic interfaces
quirk-variance-annotations - — Guard against structural typing escape hatches
quirk-structural-typing-escapes
- — 理解对象字面量的多余属性检查机制
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
参考文件
| File | Description |
|---|---|
| references/_sections.md | Category definitions and ordering |
| assets/templates/_template.md | Template for new rules |
| metadata.json | Version and reference information |
| 文件 | 描述 |
|---|---|
| references/_sections.md | 类别定义与排序规则 |
| assets/templates/_template.md | 新规则模板 |
| metadata.json | 版本与参考信息 |