typescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript Best Practices

TypeScript最佳实践

Comprehensive TypeScript 7-compatible guide with 44 rules across 8 categories, covering compiler configuration, type-system performance, async code, modules, safety, and measured runtime optimization.
这是一份兼容TypeScript 7的综合指南,包含8个类别下的44条规则,覆盖编译器配置、类型系统性能、异步代码、模块、安全性及可量化的运行时优化。

When to Apply

适用场景

Reference these guidelines when:
  • Configuring tsconfig.json for a new or existing project
  • Writing complex type definitions or generics
  • Optimizing async/await patterns and data fetching
  • Organizing modules and managing imports
  • Reviewing code for compilation or runtime performance
在以下场景中参考本指南:
  • 为新项目或现有项目配置tsconfig.json
  • 编写复杂类型定义或泛型
  • 优化async/await模式与数据获取
  • 组织模块并管理导入
  • 审查代码以优化编译或运行时性能

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Type System PerformanceCRITICAL
type-
2Compiler ConfigurationCRITICAL
tscfg-
3Async PatternsHIGH
async-
4Module OrganizationHIGH
module-
5Type Safety PatternsMEDIUM-HIGH
safety-
6Memory ManagementMEDIUM
mem-
7Runtime OptimizationLOW-MEDIUM
runtime-
8Advanced PatternsLOW
advanced-
PriorityCategoryImpactPrefix
1类型系统性能关键
type-
2编译器配置关键
tscfg-
3异步模式
async-
4模块组织
module-
5类型安全模式中高
safety-
6内存管理
mem-
7运行时优化低中
runtime-
8高级模式
advanced-

Table of Contents

目录

  1. Type System Performance — CRITICAL
    • 1.1 Add Explicit Return Types to Exported Functions — CRITICAL (faster declaration emit)
    • 1.2 Avoid Deeply Nested Generic Types — CRITICAL (prevents exponential instantiation cost)
    • 1.3 Avoid Large Union Types — CRITICAL (quadratic O(n²) comparison cost)
    • 1.4 Extract Conditional Types to Named Aliases — CRITICAL (enables compiler caching, prevents re-evaluation)
    • 1.5 Limit Type Recursion Depth — CRITICAL (prevents exponential type expansion)
    • 1.6 Prefer Interfaces Over Type Intersections — CRITICAL (faster type resolution)
    • 1.7 Simplify Complex Mapped Types — CRITICAL (reduces type computation)
  2. Compiler Configuration — CRITICAL
    • 2.1 Configure Include and Exclude Properly — CRITICAL (prevents scanning thousands of unnecessary files)
    • 2.2 Enable Incremental Compilation — CRITICAL (faster rebuilds)
    • 2.3 Choose skipLibCheck Deliberately — CRITICAL (faster compilation)
    • 2.4 Enable strictFunctionTypes for Sound Function Assignments — CRITICAL (enables optimized variance checking)
    • 2.5 Use isolatedModules for Single-File Transpilers — CRITICAL (faster transpilation with bundlers)
    • 2.6 Use Project References for Large Codebases — CRITICAL (faster incremental builds)
    • 2.7 Migrate TypeScript 7 Configuration Deliberately — CRITICAL
  3. Async Patterns — HIGH
    • 3.1 Annotate Async Function Return Types — HIGH (prevents runtime errors, improves inference)
    • 3.2 Avoid await Inside Loops — HIGH (scales linearly with the number of iterations)
    • 3.3 Avoid Unnecessary async/await — HIGH (eliminates microtask queue overhead)
    • 3.4 Defer await Until Value Is Needed — HIGH (enables implicit parallelization)
    • 3.5 Use Promise.all for Independent Operations — HIGH (improvement in I/O-bound code)
  4. Module Organization — HIGH
    • 4.1 Avoid Barrel File Imports — HIGH (import cost, larger bundles)
    • 4.2 Avoid Circular Dependencies — HIGH (prevents runtime undefined errors and slow compilation)
    • 4.3 Control @types Package Inclusion — HIGH (prevents type conflicts and reduces memory usage)
    • 4.4 Use Dynamic Imports for Large Modules — HIGH (reduces initial bundle)
    • 4.5 Use Type-Only Imports for Types — HIGH (eliminates runtime imports for type information)
  5. Type Safety Patterns — MEDIUM-HIGH
    • 5.1 Enable strictNullChecks — MEDIUM-HIGH
    • 5.2 Prefer unknown Over any — MEDIUM-HIGH
    • 5.3 Use Assertion Functions for Validation — MEDIUM-HIGH
    • 5.4 Use const Assertions for Literal Types — MEDIUM-HIGH
    • 5.5 Use Exhaustive Checks for Union Types — MEDIUM-HIGH
    • 5.6 Use Type Guards for Runtime Type Checking — MEDIUM-HIGH
  6. Memory Management — MEDIUM
    • 6.1 Avoid Closure Memory Leaks — MEDIUM (prevents retained references in long-lived callbacks)
    • 6.2 Avoid Global State Accumulation — MEDIUM (prevents unbounded memory growth)
    • 6.3 Clean Up Event Listeners — MEDIUM (prevents unbounded memory growth)
    • 6.4 Clear Timers and Intervals — MEDIUM (prevents callback retention and repeated execution)
    • 6.5 Use WeakMap for Object Metadata — MEDIUM (prevents memory leaks, enables automatic cleanup)
  7. Runtime Optimization — LOW-MEDIUM
    • 7.1 Avoid Object Spread in Hot Loops — LOW-MEDIUM
    • 7.2 Hoist Loop-Invariant Work in Measured Hot Paths — LOW-MEDIUM
    • 7.3 Prefer Native Array Methods Over Lodash — LOW-MEDIUM
    • 7.4 Use for-of for Simple Iteration — LOW-MEDIUM
    • 7.5 Use Modern String Methods — LOW-MEDIUM
    • 7.6 Use Set/Map for O(1) Lookups — LOW-MEDIUM
  8. Advanced Patterns — LOW
    • 8.1 Use Branded Types for Type-Safe IDs — LOW (prevents mixing incompatible ID types)
    • 8.2 Use satisfies for Type Validation with Inference — LOW (prevents property access errors, enables reliable autocomplete)
    • 8.3 Use Template Literal Types for String Patterns — LOW (prevents string format errors at compile time)
  1. 类型系统性能 — 关键
    • 1.1 为导出函数添加显式返回类型 — 关键(加快声明生成速度)
    • 1.2 避免深度嵌套泛型类型 — 关键(防止指数级实例化成本)
    • 1.3 避免大型联合类型 — 关键(避免二次方O(n²)的比较成本)
    • 1.4 将条件类型提取为命名别名 — 关键(启用编译器缓存,防止重复求值)
    • 1.5 限制类型递归深度 — 关键(防止指数级类型扩张)
    • 1.6 优先使用接口而非类型交集 — 关键(加快类型解析速度)
    • 1.7 简化复杂映射类型 — 关键(减少类型计算量)
  2. 编译器配置 — 关键
    • 2.1 正确配置Include与Exclude — 关键(避免扫描数千个不必要的文件)
    • 2.2 启用增量编译 — 关键(加快重建速度)
    • 2.3 谨慎选择skipLibCheck — 关键(加快编译速度)
    • 2.4 启用strictFunctionTypes以实现可靠的函数赋值 — 关键(启用优化的方差检查)
    • 2.5 为单文件转译器使用isolatedModules — 关键(加快打包工具的转译速度)
    • 2.6 为大型代码库使用项目引用 — 关键(加快增量构建速度)
    • 2.7 谨慎迁移TypeScript 7配置 — 关键
  3. 异步模式 —
    • 3.1 为异步函数标注返回类型 — 高(防止运行时错误,提升推断能力)
    • 3.2 避免在循环内使用await — 高(随迭代次数线性扩展)
    • 3.3 避免不必要的async/await — 高(消除微任务队列开销)
    • 3.4 延迟await直到需要值时 — 高(启用隐式并行化)
    • 3.5 对独立操作使用Promise.all — 高(提升I/O密集型代码的性能)
  4. 模块组织 —
    • 4.1 避免桶文件导入 — 高(降低导入成本,减小打包体积)
    • 4.2 避免循环依赖 — 高(防止运行时undefined错误和编译缓慢)
    • 4.3 控制@types包的引入 — 高(防止类型冲突并减少内存占用)
    • 4.4 对大型模块使用动态导入 — 高(减小初始打包体积)
    • 4.5 对类型使用仅类型导入 — 高(消除类型信息的运行时导入)
  5. 类型安全模式 — 中高
    • 5.1 启用strictNullChecks — 中高
    • 5.2 优先使用unknown而非any — 中高
    • 5.3 使用断言函数进行验证 — 中高
    • 5.4 对字面量类型使用const断言 — 中高
    • 5.5 对联合类型使用穷尽检查 — 中高
    • 5.6 使用类型守卫进行运行时类型检查 — 中高
  6. 内存管理 —
    • 6.1 避免闭包内存泄漏 — 中(防止长生命周期回调中保留引用)
    • 6.2 避免全局状态累积 — 中(防止内存无限增长)
    • 6.3 清理事件监听器 — 中(防止内存无限增长)
    • 6.4 清除定时器与间隔器 — 中(防止回调保留和重复执行)
    • 6.5 对对象元数据使用WeakMap — 中(防止内存泄漏,启用自动清理)
  7. 运行时优化 — 低中
    • 7.1 避免在热循环中使用对象展开 — 低中
    • 7.2 在已量化的热路径中提升循环不变操作 — 低中
    • 7.3 优先使用原生数组方法而非Lodash — 低中
    • 7.4 对简单迭代使用for-of — 低中
    • 7.5 使用现代字符串方法 — 低中
    • 7.6 使用Set/Map实现O(1)查找 — 低中
  8. 高级模式 —
    • 8.1 使用品牌类型实现类型安全的ID — 低(防止混合不兼容的ID类型)
    • 8.2 使用satisfies进行带推断的类型验证 — 低(防止属性访问错误,启用可靠的自动补全)
    • 8.3 使用模板字面量类型处理字符串模式 — 低(在编译时防止字符串格式错误)

References

参考资料