typescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript Best Practices

TypeScript最佳实践

Comprehensive performance optimization guide for TypeScript applications. Contains 42 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
TypeScript应用的全面性能优化指南。包含8个类别共42条规则,按影响程度排序,用于指导自动化重构和代码生成。

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-
优先级类别影响程度前缀
1类型系统性能关键
type-
2编译器配置关键
tscfg-
3异步模式
async-
4模块组织
module-
5类型安全模式中高
safety-
6内存管理
mem-
7运行时优化中低
runtime-
8高级模式
advanced-

Table of Contents

目录

  1. Type System PerformanceCRITICAL
    • 1.1 Add Explicit Return Types to Exported Functions — CRITICAL (30-50% 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 (2-5× faster type resolution)
    • 1.7 Simplify Complex Mapped Types — CRITICAL (reduces type computation by 50-80%)
  2. Compiler ConfigurationCRITICAL
    • 2.1 Configure Include and Exclude Properly — CRITICAL (prevents scanning thousands of unnecessary files)
    • 2.2 Enable Incremental Compilation — CRITICAL (50-90% faster rebuilds)
    • 2.3 Enable skipLibCheck for Faster Builds — CRITICAL (20-40% faster compilation)
    • 2.4 Enable strictFunctionTypes for Faster Variance Checks — CRITICAL (enables optimized variance checking)
    • 2.5 Use isolatedModules for Single-File Transpilation — CRITICAL (80-90% faster transpilation with bundlers)
    • 2.6 Use Project References for Large Codebases — CRITICAL (60-80% faster incremental builds)
  3. Async PatternsHIGH
    • 3.1 Annotate Async Function Return Types — HIGH (prevents runtime errors, improves inference)
    • 3.2 Avoid await Inside Loops — HIGH (N× faster for N iterations, 10 users = 10× improvement)
    • 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 (2-10× improvement in I/O-bound code)
  4. Module OrganizationHIGH
    • 4.1 Avoid Barrel File Imports — HIGH (200-800ms import cost, 30-50% 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 by 30-70%)
    • 4.5 Use Type-Only Imports for Types — HIGH (eliminates runtime imports for type information)
  5. Type Safety PatternsMEDIUM-HIGH
    • 5.1 Enable strictNullChecks — MEDIUM-HIGH (prevents null/undefined runtime errors)
    • 5.2 Prefer unknown Over any — MEDIUM-HIGH (forces type narrowing, prevents runtime errors)
    • 5.3 Use Assertion Functions for Validation — MEDIUM-HIGH (reduces validation boilerplate by 50-70%)
    • 5.4 Use const Assertions for Literal Types — MEDIUM-HIGH (preserves literal types, enables better inference)
    • 5.5 Use Exhaustive Checks for Union Types — MEDIUM-HIGH (prevents 100% of missing case errors at compile time)
    • 5.6 Use Type Guards for Runtime Type Checking — MEDIUM-HIGH (eliminates type assertions, catches errors at boundaries)
  6. Memory ManagementMEDIUM
    • 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 OptimizationLOW-MEDIUM
    • 7.1 Avoid Object Spread in Hot Loops — LOW-MEDIUM (reduces object allocations by N×)
    • 7.2 Cache Property Access in Loops — LOW-MEDIUM (reduces property lookups by N×)
    • 7.3 Prefer Native Array Methods Over Lodash — LOW-MEDIUM (eliminates library overhead, enables tree-shaking)
    • 7.4 Use for-of for Simple Iteration — LOW-MEDIUM (reduces iteration boilerplate by 30-50%)
    • 7.5 Use Modern String Methods — LOW-MEDIUM (2-5× faster than regex for simple patterns)
    • 7.6 Use Set/Map for O(1) Lookups — LOW-MEDIUM (O(n) to O(1) per lookup)
  8. Advanced PatternsLOW
    • 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 100% autocomplete accuracy)
    • 8.3 Use Template Literal Types for String Patterns — LOW (prevents 100% of string format errors at compile time)
  1. 类型系统性能关键
    • 1.1 为导出函数添加显式返回类型 — 关键(声明生成速度提升30-50%)
    • 1.2 避免深度嵌套的泛型类型 — 关键(防止指数级实例化成本)
    • 1.3 避免大型联合类型 — 关键(避免二次方O(n²)的比较成本)
    • 1.4 将条件类型提取为命名别名 — 关键(启用编译器缓存,防止重复计算)
    • 1.5 限制类型递归深度 — 关键(防止指数级类型扩展)
    • 1.6 优先使用接口而非类型交集 — 关键(类型解析速度提升2-5倍)
    • 1.7 简化复杂的映射类型 — 关键(减少50-80%的类型计算量)
  2. 编译器配置关键
    • 2.1 正确配置Include和Exclude — 关键(避免扫描数千个不必要的文件)
    • 2.2 启用增量编译 — 关键(重构速度提升50-90%)
    • 2.3 启用skipLibCheck以加快构建速度 — 关键(编译速度提升20-40%)
    • 2.4 启用strictFunctionTypes以加快方差检查 — 关键(启用优化的方差检查)
    • 2.5 使用isolatedModules进行单文件转译 — 关键(结合打包器使用时转译速度提升80-90%)
    • 2.6 为大型代码库使用项目引用 — 关键(增量构建速度提升60-80%)
  3. 异步模式
    • 3.1 为异步函数标注返回类型 — 高(防止运行时错误,提升推断能力)
    • 3.2 避免在循环内使用await — 高(N次迭代速度提升N倍,10次迭代=10倍提升)
    • 3.3 避免不必要的async/await — 高(消除微任务队列开销)
    • 3.4 延迟await直到需要该值时 — 高(启用隐式并行处理)
    • 3.5 使用Promise.all处理独立操作 — 高(I/O密集型代码性能提升2-10倍)
  4. 模块组织
    • 4.1 避免桶文件导入 — 高(导入成本200-800ms,包体积增大30-50%)
    • 4.2 避免循环依赖 — 高(防止运行时undefined错误和编译缓慢)
    • 4.3 控制@types包的引入 — 高(防止类型冲突并减少内存使用)
    • 4.4 为大型模块使用动态导入 — 高(初始包体积减少30-70%)
    • 4.5 为类型使用仅类型导入 — 高(消除类型信息的运行时导入)
  5. 类型安全模式中高
    • 5.1 启用strictNullChecks — 中高(防止null/undefined运行时错误)
    • 5.2 优先使用unknown而非any — 中高(强制类型收窄,防止运行时错误)
    • 5.3 使用断言函数进行验证 — 中高(减少50-70%的验证样板代码)
    • 5.4 为字面量类型使用const断言 — 中高(保留字面量类型,提升推断能力)
    • 5.5 为联合类型使用穷尽检查 — 中高(在编译时100%防止遗漏分支错误)
    • 5.6 使用类型守卫进行运行时类型检查 — 中高(消除类型断言,在边界处捕获错误)
  6. 内存管理
    • 6.1 避免闭包内存泄漏 — 中(防止长期回调中保留引用)
    • 6.2 避免全局状态累积 — 中(防止无限制的内存增长)
    • 6.3 清理事件监听器 — 中(防止无限制的内存增长)
    • 6.4 清除定时器和间隔器 — 中(防止回调保留和重复执行)
    • 6.5 使用WeakMap存储对象元数据 — 中(防止内存泄漏,启用自动清理)
  7. 运行时优化中低
    • 7.1 避免在热循环中使用对象展开 — 中低(减少N倍的对象分配)
    • 7.2 在循环中缓存属性访问 — 中低(减少N倍的属性查找)
    • 7.3 优先使用原生数组方法而非Lodash — 中低(消除库开销,启用摇树优化)
    • 7.4 使用for-of进行简单迭代 — 中低(减少30-50%的迭代样板代码)
    • 7.5 使用现代字符串方法 — 中低(简单模式下比正则快2-5倍)
    • 7.6 使用Set/Map实现O(1)查找 — 中低(每次查找从O(n)变为O(1))
  8. 高级模式
    • 8.1 使用品牌类型实现类型安全的ID — 低(防止混合不兼容的ID类型)
    • 8.2 使用satisfies进行带推断的类型验证 — 低(防止属性访问错误,实现100%自动补全准确率)
    • 8.3 使用模板字面量类型处理字符串模式 — 低(在编译时100%防止字符串格式错误)

References

参考资料