typescript-expert
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript Expert
TypeScript 专家指南
Covers TypeScript through 5.8 (latest stable as of March 2026). The official handbook at https://www.typescriptlang.org/docs/handbook/ is the canonical reference.
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Its type system is structural (not nominal), meaning type compatibility is determined by shape rather than declaration. This has profound implications for how you design types and APIs.
涵盖至TypeScript 5.8版本(截至2026年3月的最新稳定版)。官方手册https://www.typescriptlang.org/docs/handbook/ 为权威参考资料。
TypeScript是JavaScript的类型化超集,可编译为普通JavaScript。它的类型系统采用结构类型(而非标称类型),即类型兼容性由形状而非声明决定。这对类型和API的设计有着深远影响。
Quick Decision Guide
快速决策指南
| You need to... | Read |
|---|---|
| Understand primitives, inference, narrowing | core-type-system |
Choose between | core-interfaces-types |
| Write generic functions, classes, constraints | core-generics |
Use | core-utility-types |
Build conditional types with | advanced-conditional-types |
| Create mapped types and key remapping | advanced-mapped-types |
| Use template literal types for string patterns | advanced-template-literals |
| Narrow types with guards and discriminated unions | advanced-type-guards |
| Use TC39 decorators (TS 5.0+) | advanced-decorators |
Configure | best-practices-tsconfig |
| Apply common patterns (branded types, error handling, immutability) | best-practices-patterns |
| Optimize type-level performance | best-practices-performance |
Use TS 5.0-5.8 features ( | features-ts5x |
| 你需要... | 阅读文档 |
|---|---|
| 理解原始类型、类型推断、类型收窄 | core-type-system |
选择 | core-interfaces-types |
| 编写泛型函数、类、约束 | core-generics |
使用 | core-utility-types |
结合 | advanced-conditional-types |
| 创建映射类型与键重映射 | advanced-mapped-types |
| 使用模板字面量类型处理字符串模式 | advanced-template-literals |
| 使用类型守卫与可辨识联合收窄类型 | advanced-type-guards |
| 使用TC39标准装饰器(TS 5.0+) | advanced-decorators |
正确配置 | best-practices-tsconfig |
| 应用常见模式(品牌类型、错误处理、不可变性) | best-practices-patterns |
| 优化类型层面性能 | best-practices-performance |
使用TS 5.0-5.8特性( | features-ts5x |
Core Principles
核心原则
1. Let TypeScript Infer
1. 尽量让TypeScript自动推断
TypeScript's inference is powerful. Don't annotate what TypeScript can figure out on its own:
typescript
// Unnecessary — TypeScript infers `number`
const count: number = 5;
// Good — let inference work
const count = 5;
// DO annotate function signatures (parameters + return types for public APIs)
function getUser(id: string): Promise<User> { ... }
// Return type annotation catches accidental returns
function parse(input: string): ParseResult {
if (!input) return null; // Error! null isn't ParseResult — good, we caught a bug
}TypeScript的推断能力很强。TypeScript能自动识别的类型,无需手动标注:
typescript
// 没必要——TypeScript会自动推断为`number`类型
const count: number = 5;
// 推荐——让推断自行工作
const count = 5;
// 公共API的函数签名必须标注(参数+返回类型)
function getUser(id: string): Promise<User> { ... }
// 返回类型标注可捕获意外返回值
function parse(input: string): ParseResult {
if (!input) return null; // 错误!null不属于ParseResult类型——很好,我们提前发现了bug
}2. Prefer unknown
over any
unknownany2. 优先使用unknown
而非any
unknownanyanyunknowntypescript
// Bad — silently breaks type safety
function process(data: any) {
data.foo.bar; // No error, but might crash at runtime
}
// Good — forces you to check before using
function process(data: unknown) {
if (typeof data === "object" && data !== null && "foo" in data) {
// Now TypeScript knows data has a foo property
}
}anyunknowntypescript
// 不推荐——悄悄破坏类型安全
function process(data: any) {
data.foo.bar; // 无编译错误,但运行时可能崩溃
}
// 推荐——强制你在使用前进行检查
function process(data: unknown) {
if (typeof data === "object" && data !== null && "foo" in data) {
// 此时TypeScript已知道data拥有foo属性
}
}3. Use Strict Mode
3. 启用严格模式
Always enable in tsconfig.json. It enables all strict type-checking flags including , , and . Projects that skip strict mode accumulate hidden bugs that surface painfully later. See best-practices-tsconfig for the full recommended configuration.
"strict": truestrictNullChecksnoImplicitAnystrictFunctionTypes始终在tsconfig.json中启用。它会开启所有严格类型检查标志,包括、和。跳过严格模式的项目会积累隐藏bug,后续排查会非常痛苦。查看best-practices-tsconfig获取完整推荐配置。
"strict": truestrictNullChecksnoImplicitAnystrictFunctionTypes4. Model Your Domain with Types
4. 用类型建模业务领域
The type system is a tool for encoding business rules. Use discriminated unions to model states, branded types for domain identifiers, and to enforce immutability:
readonlytypescript
// Model states explicitly — impossible to access data in loading/error state
type AsyncState<T> =
| { status: "loading" }
| { status: "error"; error: Error }
| { status: "success"; data: T };
// Branded types prevent ID mixups at compile time
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function getOrder(orderId: OrderId): Order { ... }
getOrder(userId); // Error! UserId is not assignable to OrderId类型系统是编码业务规则的工具。使用可辨识联合建模状态,品牌类型建模领域标识符,强制不可变性:
readonlytypescript
// 显式建模状态——无法在加载/错误状态下访问数据
type AsyncState<T> =
| { status: "loading" }
| { status: "error"; error: Error }
| { status: "success"; data: T };
// 品牌类型可在编译期防止ID混用
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function getOrder(orderId: OrderId): Order { ... }
getOrder(userId); // 错误!UserId无法赋值给OrderId5. Structural Typing Implications
5. 结构类型的影响
TypeScript uses structural typing — if two types have the same shape, they're compatible:
typescript
interface Point { x: number; y: number }
interface Coordinate { x: number; y: number }
const p: Point = { x: 1, y: 2 };
const c: Coordinate = p; // OK — same shape
// This means excess property checks only apply to object literals
function plot(point: Point) { ... }
plot({ x: 1, y: 2, z: 3 }); // Error — excess property check on literal
const obj = { x: 1, y: 2, z: 3 };
plot(obj); // OK — no excess check on variableTypeScript采用结构类型——若两个类型形状相同,则它们兼容:
typescript
interface Point { x: number; y: number }
interface Coordinate { x: number; y: number }
const p: Point = { x: 1, y: 2 };
const c: Coordinate = p; // 允许——形状相同
// 这意味着多余属性检查仅适用于对象字面量
function plot(point: Point) { ... }
plot({ x: 1, y: 2, z: 3 }); // 错误——对字面量进行多余属性检查
const obj = { x: 1, y: 2, z: 3 };
plot(obj); // 允许——对变量不进行多余属性检查Common Gotchas
常见陷阱
| Gotcha | Explanation |
|---|---|
| Use |
| Arrays are mutable by default. Use |
| Prefer union types ( |
Optional vs | |
| Type assertions ( |
| A single |
| 陷阱 | 说明 |
|---|---|
| 用 |
| 数组默认是可变的。当不需要修改时,使用 |
| 优先使用联合类型( |
可选属性 vs | |
| 类型断言( |
| 单个 |
TypeScript 5.x Highlights
TypeScript 5.x 重要特性
Key features added in TypeScript 5.0-5.8 (see features-ts5x for details):
| Version | Feature | Why it matters |
|---|---|---|
| 5.0 | TC39 Decorators | Standard decorator syntax, no |
| 5.0 | | |
| 5.1 | Easier implicit returns | |
| 5.2 | | Deterministic resource cleanup (like C# |
| 5.4 | | Prevents unwanted inference from specific positions |
| 5.5 | Inferred type predicates | |
| 5.6 | Iterator helper methods | |
| 5.7 | | Faster composite project builds |
| 5.8 | | Strip types without full compilation (Node.js |
TypeScript 5.0-5.8版本新增的关键特性(详情见features-ts5x):
| 版本 | 特性 | 重要性 |
|---|---|---|
| 5.0 | TC39标准装饰器 | 标准装饰器语法,无需启用 |
| 5.0 | | |
| 5.1 | 更宽松的隐式返回 | 返回 |
| 5.2 | | 确定性资源清理(类似C#的 |
| 5.4 | | 防止特定位置出现不必要的类型推断 |
| 5.5 | 推断类型谓词 | |
| 5.6 | 迭代器辅助方法 | 迭代器支持 |
| 5.7 | 项目引用的 | 复合项目构建速度更快 |
| 5.8 | | 无需完整编译即可剥离类型(支持Node.js |
When to Read the References
何时查阅参考文档
- Writing a new module/library: Read core-generics and best-practices-patterns
- Debugging a confusing type error: Read advanced-type-guards and core-type-system
- Designing a type-safe API: Read advanced-conditional-types and advanced-mapped-types
- Setting up a new project: Read best-practices-tsconfig
- Migrating from JS or older TS: Read features-ts5x and best-practices-tsconfig
- Performance issues with types: Read best-practices-performance
- 编写新模块/库:阅读core-generics和best-practices-patterns
- 调试复杂类型错误:阅读advanced-type-guards和core-type-system
- 设计类型安全的API:阅读advanced-conditional-types和advanced-mapped-types
- 搭建新项目:阅读best-practices-tsconfig
- 从JS或旧版TS迁移:阅读features-ts5x和best-practices-tsconfig
- 类型层面性能问题:阅读best-practices-performance