typescript-advanced-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript 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:
- Conditional Types: Type selection based on conditions (type-level if/else)
- Mapped Types: Transform object types systematically (Partial, Readonly, Pick, Omit)
- Template Literal Types: String manipulation at compile time
- Type Guards: Runtime checking with type narrowing ()
value is Type - Discriminated Unions: Type-safe state machines with exhaustiveness checking
- Branded Types: Nominal types for preventing primitive mixing
- Builder Pattern: Type-safe fluent APIs with progressive type constraints
- Advanced Generics: Constraints, inference, and higher-kinded type patterns
- Utility Types: Deep transformations and compositions
- Type Inference: Const assertions and contextual typing
TypeScript的类型系统通过以下特性实现编译时安全:
- Conditional Types:基于条件的类型选择(类型层面的if/else)
- Mapped Types:系统性转换对象类型(Partial、Readonly、Pick、Omit)
- Template Literal Types:编译时字符串操作
- Type Guards:带有类型收窄的运行时检查()
value is Type - Discriminated Unions:具备穷尽性检查的类型安全状态机
- Branded Types:用于防止原始类型混淆的标称类型
- Builder Pattern:带有渐进式类型约束的类型安全流畅API
- Advanced Generics:约束、推断和高阶类型模式
- Utility Types:深度转换和组合
- Type Inference:const断言和上下文类型
Quick Reference
快速参考
Load detailed references on-demand:
| Topic | Reference File |
|---|---|
| Conditional Types | |
| Mapped Types | |
| Template Literal Types | |
| Type Guards | |
| Discriminated Unions | |
| Branded Types | |
| Builder Pattern | |
| Advanced Generics | |
| Utility Types | |
| Type Inference | |
| Decorators | |
| Performance Best Practices | |
| Common Pitfalls | |
| Testing Types | |
按需加载详细参考文档:
| 主题 | 参考文件 |
|---|---|
| Conditional Types | |
| Mapped Types | |
| Template Literal Types | |
| Type Guards | |
| Discriminated Unions | |
| Branded Types | |
| Builder Pattern | |
| Advanced Generics | |
| Utility Types | |
| Type Inference | |
| Decorators | |
| Performance Best Practices | |
| Common Pitfalls | |
| Testing Types | |
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 (with
tsconfig.json)"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
需避免的常见错误
-
Usinginstead of
any: Loses all type safetyunknown- Use and type guards instead
unknown
- Use
-
Type assertions without validation: Unsafe runtime behavior
- Prefer type guards () over
value is Typeas Type
- Prefer type guards (
-
Overusing generics: Unnecessary complexity
- Only use generics when types truly vary
-
Deep type nesting: Slow compilation, hard to debug
- Keep types composable and shallow
-
Forgetting: Accidental mutations
readonly- Mark immutable data structures as
readonly
- Mark immutable data structures as
-
Not enabling strict mode: Missing null checks and type errors
- Always use in
"strict": truetsconfig.json
- Always use
-
Mixing type and interface incorrectly: Confusing semantics
- Use for unions/utilities,
typefor object shapesinterface
- Use
-
使用而非
any:完全失去类型安全unknown- 改用和类型守卫
unknown
- 改用
-
无验证的类型断言:导致不安全的运行时行为
- 优先使用类型守卫()而非
value is Typeas Type
- 优先使用类型守卫(
-
过度使用泛型:造成不必要的复杂度
- 仅在类型确实需要变化时使用泛型
-
深层类型嵌套:编译缓慢,难以调试
- 保持类型可组合且层级较浅
-
忘记:导致意外的突变
readonly- 将不可变数据结构标记为
readonly
- 将不可变数据结构标记为
-
未启用严格模式:遗漏空值检查和类型错误
- 始终在中设置
tsconfig.json"strict": true
- 始终在
-
错误混用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
资源
- TypeScript Handbook: https://www.typescriptlang.org/docs/handbook/
- Type Challenges: https://github.com/type-challenges/type-challenges
- ts-toolbelt: Advanced type utilities library
- zod: Runtime validation with TypeScript inference
- tsd: Test TypeScript type definitions
- TypeScript Handbook: https://www.typescriptlang.org/docs/handbook/
- Type Challenges: https://github.com/type-challenges/type-challenges
- ts-toolbelt: 高级类型工具库
- zod: 具备TypeScript推断能力的运行时验证库
- tsd: TypeScript类型定义测试工具