| name | typescript-best-practices |
| description | Use when writing or reviewing TypeScript for type safety, advanced types, API boundaries, strict-mode migrations, and common anti-pattern avoidance. |
| zh_description | 用于 TypeScript 类型安全设计、高级类型、API 边界、strict 迁移和反模式规避。 |
| version | 1.0.0 |
| author | seaworld008 |
| source | in-house |
| source_url | |
| tags | ["best", "development", "practices", "typescript"] |
| created_at | 2026-03-27 |
| updated_at | 2026-06-29 |
| quality | 4 |
| complexity | intermediate |
TypeScript Best Practices
TypeScript is more than just "JavaScript with types." It is a powerful structural type system that can provide profound safety if used correctly. This skill guides you through professional patterns and advanced type programming.
触发条件
- 正在启动一个新的中大型 Web 项目(React/Vue/Node.js)。
- 需要重构现有的 JS 代码库,并引入类型安全。
- 正在开发一个面向外部开发者的 npm 包。
- 需要在 monorepo 架构中管理跨项目的共享类型定义。
- 团队代码库中充斥着大量的
any 或 as any,亟需纠正。
核心能力
1. 高级类型 (Advanced Types)
- Conditional Types: 依据类型 T 的属性返回不同的类型 U 或 V(如
T extends U ? X : Y)。
- Template Literal Types: 使用模板字符串语法操作字符串字面量类型。
- Mapped Types: 基于现有类型生成新类型(如
Partial, Readonly, Record)。
- Utility Types: 合理组合内置工具类,实现灵活的数据模型定义。
2. 类型守卫 (Type Guards & Assertions)
- User-Defined Guards: 使用
is 关键字编写自定义判断函数。
- In/Instanceof/Typeof: 在运行时进行收缩(Type Narrowing)。
- Assertion Functions: 结合测试或异常处理的类型断言。
3. 泛型约束 (Generic Constraints)
- Extends Keyword: 为泛型注入约束条件,确保类型具备某些属性。
- Default Generic Types: 提供合理的缺省值以简化 API。
- Generic Inference: 利用 TypeScript 的推断能力,减少显式声明。
4. 可辨识联合 (Discriminated Unions)
这是 TS 处理多种状态(如 Loading/Success/Error)的最佳实践。
- Common Property: 定义一个共同的、单值(literal)属性(如
kind, type, status)。
- Exhaustiveness Checking: 使用
never 类型确保 switch/case 覆盖了所有可能的分支。
5. 运行时校验 (Zod/Valibot)
TypeScript 仅在编译时有效。对于外部数据(API 响应、表单输入),必须在运行时校验。
- Schema First: 先定义 Zod Schema,再利用
z.infer<T> 生成静态类型。
- Safe Parsing: 优雅处理校验失败,并提供语义化的错误信息。
- Coercion: 自动进行简单的数据转换(如字符串转数字)。
6. tsconfig 最佳配置
- strict: true: 这是所有生产项目的起点。
- exactOptionalPropertyTypes: 区分
undefined 和“未设置”。