typescript-advanced-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript Advanced Patterns

TypeScript 高级模式

Expert guidance for leveraging TypeScript's advanced type system features to build robust, type-safe applications with sophisticated type inference, compile-time guarantees, and maintainable domain models.
本指南提供专家级指导,教你如何利用TypeScript的高级类型系统特性,构建具备复杂类型推断、编译时保障和可维护领域模型的健壮、类型安全应用。

When to Use This Skill

何时使用此技能

  • Building type-safe APIs with strict contracts and validation
  • Implementing complex domain models with compile-time enforcement
  • Creating reusable libraries with sophisticated type inference
  • Enforcing business rules through the type system
  • Building type-safe state machines and builders
  • Developing framework integrations requiring advanced types
  • Implementing runtime validation with type-level guarantees
  • 构建具有严格契约和验证的类型安全API
  • 实现具备编译时约束的复杂领域模型
  • 创建具备复杂类型推断的可复用库
  • 通过类型系统执行业务规则
  • 构建类型安全的状态机和构建器
  • 开发需要高级类型的框架集成
  • 实现带有类型层面保障的运行时验证

Core Concepts

核心概念

TypeScript's type system enables compile-time safety through:
  1. Conditional Types: Type selection based on conditions (type-level if/else)
  2. Mapped Types: Transform object types systematically (Partial, Readonly, Pick, Omit)
  3. Template Literal Types: String manipulation at compile time
  4. Type Guards: Runtime checking with type narrowing (
    value is Type
    )
  5. Discriminated Unions: Type-safe state machines with exhaustiveness checking
  6. Branded Types: Nominal types for preventing primitive mixing
  7. Builder Pattern: Type-safe fluent APIs with progressive type constraints
  8. Advanced Generics: Constraints, inference, and higher-kinded type patterns
  9. Utility Types: Deep transformations and compositions
  10. Type Inference: Const assertions and contextual typing
TypeScript的类型系统通过以下特性实现编译时安全:
  1. Conditional Types:基于条件的类型选择(类型层面的if/else)
  2. Mapped Types:系统性转换对象类型(Partial、Readonly、Pick、Omit)
  3. Template Literal Types:编译时字符串操作
  4. Type Guards:带有类型收窄的运行时检查(
    value is Type
  5. Discriminated Unions:具备穷尽性检查的类型安全状态机
  6. Branded Types:用于防止原始类型混淆的标称类型
  7. Builder Pattern:带有渐进式类型约束的类型安全流畅API
  8. Advanced Generics:约束、推断和高阶类型模式
  9. Utility Types:深度转换和组合
  10. Type Inference:const断言和上下文类型

Quick Reference

快速参考

Load detailed references on-demand:
TopicReference File
Conditional Types
skills/typescript-advanced-patterns/references/conditional-types.md
Mapped Types
skills/typescript-advanced-patterns/references/mapped-types.md
Template Literal Types
skills/typescript-advanced-patterns/references/template-literal-types.md
Type Guards
skills/typescript-advanced-patterns/references/type-guards.md
Discriminated Unions
skills/typescript-advanced-patterns/references/discriminated-unions.md
Branded Types
skills/typescript-advanced-patterns/references/branded-types.md
Builder Pattern
skills/typescript-advanced-patterns/references/builder-pattern.md
Advanced Generics
skills/typescript-advanced-patterns/references/advanced-generics.md
Utility Types
skills/typescript-advanced-patterns/references/utility-types.md
Type Inference
skills/typescript-advanced-patterns/references/type-inference.md
Decorators
skills/typescript-advanced-patterns/references/decorators.md
Performance Best Practices
skills/typescript-advanced-patterns/references/performance-best-practices.md
Common Pitfalls
skills/typescript-advanced-patterns/references/common-pitfalls.md
Testing Types
skills/typescript-advanced-patterns/references/testing-types.md
按需加载详细参考文档:
主题参考文件
Conditional Types
skills/typescript-advanced-patterns/references/conditional-types.md
Mapped Types
skills/typescript-advanced-patterns/references/mapped-types.md
Template Literal Types
skills/typescript-advanced-patterns/references/template-literal-types.md
Type Guards
skills/typescript-advanced-patterns/references/type-guards.md
Discriminated Unions
skills/typescript-advanced-patterns/references/discriminated-unions.md
Branded Types
skills/typescript-advanced-patterns/references/branded-types.md
Builder Pattern
skills/typescript-advanced-patterns/references/builder-pattern.md
Advanced Generics
skills/typescript-advanced-patterns/references/advanced-generics.md
Utility Types
skills/typescript-advanced-patterns/references/utility-types.md
Type Inference
skills/typescript-advanced-patterns/references/type-inference.md
Decorators
skills/typescript-advanced-patterns/references/decorators.md
Performance Best Practices
skills/typescript-advanced-patterns/references/performance-best-practices.md
Common Pitfalls
skills/typescript-advanced-patterns/references/common-pitfalls.md
Testing Types
skills/typescript-advanced-patterns/references/testing-types.md

Implementation Workflow

实现工作流

1. Identify Pattern Need

1. 识别模式需求

  • Analyze type safety requirements
  • Identify runtime vs compile-time constraints
  • Choose appropriate pattern from Quick Reference
  • 分析类型安全要求
  • 识别运行时与编译时约束
  • 从快速参考中选择合适的模式

2. Load Reference

2. 加载参考文档

  • Read specific reference file for pattern
  • Review examples and use cases
  • Understand trade-offs
  • 阅读对应模式的参考文件
  • 查看示例和用例
  • 了解权衡点

3. Implement Pattern

3. 实现模式

  • Start simple, add complexity as needed
  • Use strict mode (
    tsconfig.json
    with
    "strict": true
    )
  • Test with type assertions
  • 从简单开始,按需增加复杂度
  • 使用严格模式(
    tsconfig.json
    中设置
    "strict": true
  • 用类型断言进行测试

4. Validate

4. 验证

  • Ensure type errors caught at compile time
  • Verify runtime behavior matches types
  • Check performance (avoid excessive type complexity)
  • 确保类型错误在编译时被捕获
  • 验证运行时行为与类型一致
  • 检查性能(避免过度复杂的类型)

5. Document

5. 文档

  • Add JSDoc comments for public APIs
  • Document type constraints and assumptions
  • Provide usage examples
  • 为公共API添加JSDoc注释
  • 记录类型约束和假设
  • 提供使用示例

Common Mistakes to Avoid

需避免的常见错误

  1. Using
    any
    instead of
    unknown
    : Loses all type safety
    • Use
      unknown
      and type guards instead
  2. Type assertions without validation: Unsafe runtime behavior
    • Prefer type guards (
      value is Type
      ) over
      as Type
  3. Overusing generics: Unnecessary complexity
    • Only use generics when types truly vary
  4. Deep type nesting: Slow compilation, hard to debug
    • Keep types composable and shallow
  5. Forgetting
    readonly
    : Accidental mutations
    • Mark immutable data structures as
      readonly
  6. Not enabling strict mode: Missing null checks and type errors
    • Always use
      "strict": true
      in
      tsconfig.json
  7. Mixing type and interface incorrectly: Confusing semantics
    • Use
      type
      for unions/utilities,
      interface
      for object shapes
  1. 使用
    any
    而非
    unknown
    :完全失去类型安全
    • 改用
      unknown
      和类型守卫
  2. 无验证的类型断言:导致不安全的运行时行为
    • 优先使用类型守卫(
      value is Type
      )而非
      as Type
  3. 过度使用泛型:造成不必要的复杂度
    • 仅在类型确实需要变化时使用泛型
  4. 深层类型嵌套:编译缓慢,难以调试
    • 保持类型可组合且层级较浅
  5. 忘记
    readonly
    :导致意外的突变
    • 将不可变数据结构标记为
      readonly
  6. 未启用严格模式:遗漏空值检查和类型错误
    • 始终在
      tsconfig.json
      中设置
      "strict": true
  7. 错误混用type和interface:语义混淆
    • type
      定义联合类型/工具类型,用
      interface
      定义对象形状

Quick Patterns

快速模式示例

Type-Safe ID

类型安全ID

typescript
type UserId = string & { readonly __brand: 'UserId' };
function createUserId(id: string): UserId { return id as UserId; }
typescript
type UserId = string & { readonly __brand: 'UserId' };
function createUserId(id: string): UserId { return id as UserId; }

Discriminated Union

区分联合类型

typescript
type State =
  | { status: 'loading' }
  | { status: 'success'; data: string }
  | { status: 'error'; error: Error };
typescript
type State =
  | { status: 'loading' }
  | { status: 'success'; data: string }
  | { status: 'error'; error: Error };

Mapped Type Transformation

映射类型转换

typescript
type Readonly<T> = { readonly [P in keyof T]: T[P] };
type Partial<T> = { [P in keyof T]?: T[P] };
typescript
type Readonly<T> = { readonly [P in keyof T]: T[P] };
type Partial<T> = { [P in keyof T]?: T[P] };

Type Guard

类型守卫

typescript
function isString(value: unknown): value is string {
  return typeof value === 'string';
}
typescript
function isString(value: unknown): value is string {
  return typeof value === 'string';
}

Resources

资源