typescript-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript Patterns
TypeScript 模式
Overview
概述
Advanced TypeScript patterns that use the type system to prevent runtime errors. Focuses on strict mode TypeScript with patterns for type inference, narrowing, and compile-time validation. Not a beginner tutorial.
When to use: Building type-safe APIs, complex data transformations, library authoring, preventing runtime errors through types, working with strict mode flags.
When NOT to use: Learning TypeScript basics (primitives, interfaces, classes), JavaScript-to-TypeScript migration guidance, tooling setup, or build configuration.
利用类型系统避免运行时错误的高级TypeScript模式。聚焦于严格模式下的TypeScript,涵盖类型推断、类型收窄与编译时验证的相关模式。这不是入门教程。
适用场景: 构建类型安全的API、复杂数据转换、库开发、通过类型避免运行时错误、使用严格模式配置项。
不适用场景: 学习TypeScript基础知识(原始类型、接口、类)、JavaScript转TypeScript迁移指导、工具搭建或构建配置。
Quick Reference
速查参考
| Pattern | API | Key Points |
|---|---|---|
| Utility types | | Extract or exclude properties |
| Partial/Required | | Make properties optional or required |
| Record type | | Object with known keys |
| Awaited type | | Unwrap Promise return types |
| ReturnType/Parameters | | Extract function types |
| Generic constraints | | Constrain generic parameters |
| Type inference | | Let TypeScript infer from values |
| Type guards | | Narrow types at runtime |
| Custom type guards | | User-defined narrowing functions |
| Inferred predicates | | Auto-inferred type predicate filters |
| Discriminated unions | Union with literal | Exhaustive pattern matching |
| Conditional types | | Type-level conditionals |
| Mapped types | | Transform all properties |
| Template literals | | String literal type manipulation |
| Const assertions | | Narrowest possible literal types |
| Satisfies operator | | Type check without widening |
| NoInfer utility | | Prevent inference from a position |
| Const type params | | Narrow inference without |
| Inline type imports | | Import types explicitly |
| Module augmentation | | Extend third-party types |
| Assertion functions | | Throw if type guard fails |
| 模式 | API | 核心要点 |
|---|---|---|
| 工具类型 | | 提取或排除属性 |
| 可选/必填转换 | | 将属性设为可选或必填 |
| Record类型 | | 拥有已知键的对象 |
| Awaited类型 | | 解开Promise返回类型 |
| 返回值/参数类型提取 | | 提取函数的类型信息 |
| 泛型约束 | | 约束泛型参数 |
| 类型推断 | | 让TypeScript从值中自动推断类型 |
| 类型守卫 | | 在运行时收窄类型范围 |
| 自定义类型守卫 | | 用户自定义的类型收窄函数 |
| 自动推断谓词 | | 自动推断的类型谓词过滤器 |
| 可辨识联合 | 包含字面量 | 穷尽式模式匹配 |
| 条件类型 | | 类型层面的条件判断 |
| 映射类型 | | 转换对象的所有属性 |
| 模板字面量类型 | | 字符串字面量类型的操作 |
| Const断言 | | 获得最窄的字面量类型 |
| Satisfies操作符 | | 类型检查同时保留窄类型 |
| NoInfer工具类型 | | 阻止从特定位置进行类型推断 |
| Const泛型参数 | | 无需 |
| 内联类型导入 | | 显式导入类型 |
| 模块扩充 | | 扩展第三方库的类型定义 |
| 断言函数 | | 若类型守卫验证失败则抛出错误 |
Common Mistakes
常见错误
| Mistake | Correct Pattern |
|---|---|
Using | Use |
| Manual type assertions everywhere | Let inference work, type function returns |
| Destructuring before type narrowing | Keep object intact for discriminated unions |
| Index access without undefined check | Enable |
| Use |
| Inline objects in generics | Extract to |
Omitting | Always constrain generics when possible |
Using | Type the parameter directly in function |
| Not handling union exhaustiveness | Use |
| Use |
| 错误做法 | 正确模式 |
|---|---|
无正当理由使用 | 使用 |
| 到处手动添加类型断言 | 让TypeScript自动推断,仅为函数返回值指定类型 |
| 在类型收窄前解构对象 | 保持对象完整以适配可辨识联合 |
| 未检查undefined就进行索引访问 | 启用 |
用 | 使用 |
| 在泛型中直接使用内联对象 | 提取为 |
约束中省略 | 尽可能为泛型添加约束 |
使用 | 在函数中直接为参数指定类型 |
| 未处理联合类型的穷尽性 | 在switch/if-else中使用 |
| 若需要则先使用 |
Delegation
任务委派
- Pattern discovery: Use agent to find existing patterns in codebase
Explore - Type error debugging: Use agent for multi-step type resolution
Task - Code review: Delegate to skill for type safety audit
code-reviewer
- 模式发现:使用agent在代码库中查找现有模式
Explore - 类型错误调试:使用agent进行多步骤类型解析
Task - 代码审查:委派给技能进行类型安全审计
code-reviewer
References
参考资料
- Type utilities (Pick, Omit, Partial, Required, Record, Extract, Exclude, ReturnType, Parameters, Awaited)
- Generics (constraints, inference, default parameters, variance)
- Type guards and narrowing (typeof, instanceof, in, custom guards, assertion functions)
- Discriminated unions (exhaustive checking, never type, tagged unions)
- Conditional types (distributive conditionals, infer keyword, type-level logic)
- Mapped types (key remapping, template literals, modifiers)
- Strict mode patterns (noUncheckedIndexedAccess, exactOptionalPropertyTypes, const assertions, satisfies)
- Module patterns (inline type imports, declaration files, module augmentation, ambient types)
- Modern idioms (eslint-plugin-unicorn patterns, modern array/string/DOM APIs, ES modules)
- 类型工具(Pick、Omit、Partial、Required、Record、Extract、Exclude、ReturnType、Parameters、Awaited)
- 泛型(约束、推断、默认参数、方差)
- 类型守卫与类型收窄(typeof、instanceof、in、自定义守卫、断言函数)
- 可辨识联合(穷尽检查、never类型、标签联合)
- 条件类型(分布式条件、infer关键字、类型层面逻辑)
- 映射类型(键重映射、模板字面量、修饰符)
- 严格模式模式(noUncheckedIndexedAccess、exactOptionalPropertyTypes、const断言、satisfies)
- 模块模式(内联类型导入、声明文件、模块扩充、环境类型)
- 现代惯用写法(eslint-plugin-unicorn模式、现代数组/字符串/DOM API、ES模块)