TypeScript 最佳实践
Production-ready TypeScript 练习: naming, 输入, 错误 handling, and 项目结构.
你将学到
- 当到 annotate 对比 rely on inference for clean code
- Avoiding 任何 and using unknown for safer 运行时数据
- Structuring 类型 alongside 源 code for maintainability
- Using discriminated unions and branded 类型 for 领域 modeling
概念讲解
Annotation Discipline
The best practice for annotations is: annotate public APIs (function signatures, exported types, class interfaces) and let inference handle local variables. Over-annotating clutters code; under-annotating public APIs makes them fragile. Function parameters always need annotations (no inference context). Return types on exported functions should be explicit — they serve as documentation and catch accidental changes. Internal locals like const result = compute(x) should rely on inference.
Avoid any, Embrace unknown
任何 disables type checking — it is a hole in your type system. Replace it with unknown for data of unknown type (API responses, parsed JSON). unknown forces you to verify the type before use, keeping safety. For runtime validation, use a library like zod that both validates data and infers TypeScript types from the schema. This gives you a single source of truth for both runtime and compile-time types.
Domain Modeling
Use discriminated unions to model domain states: 类型 RequestState = Idle | 加载 | 成功 | 错误 with a common 状态 field. This makes impossible states unrepresentable — the compiler ensures you handle every case. Use branded types (also called opaque types) for domain identifiers: 类型 UserId = 字符串 & { __brand: "UserId" } prevents mixing a UserId with a plain string. These patterns push more logic into the type system, catching bugs at compile time rather than runtime.
示例代码
// Best practice: discriminated union for state management.
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: string };
function handleState<T>(state: RequestState<T>): string {
switch (state.status) {
case "idle": return "Ready to start";
case "loading": return "Please wait...";
case "success": return `Got: ${state.data}`;
case "error": return `Failed: ${state.error}`;
}
}
// Best practice: branded type for type-safe IDs.
type UserId = string & { readonly __brand: "UserId" };
function createUserId(id: string): UserId {
return id as UserId;
}
function getUser(id: UserId): string {
return `User ${id}`;
}
// Best practice: unknown for untrusted data.
function parseInput(raw: unknown): string {
if (typeof raw === "string" && raw.length > 0) {
return raw;
}
throw new Error("Invalid input");
}
const state: RequestState<number> = { status: "success", data: 42 };
const uid = createUserId("u123");
console.log(handleState(state));
console.log(getUser(uid));
console.log(parseInput("hello"));
Annotate 公共 APIs, infer locals. Replace 任何使用 unknown for untrusted 数据. Use discriminated unions 到 model 状态 and branded 类型 for 领域 IDs. 这些练习 catch bugs at 编译时间.
动手试一试
- JSON 到 TypeScript
Generate 类型从 API 响应 as 开始点 for 领域 modeling.
- JSON Schema Validator
运行时 validation complements 编译-时间类型 — 验证之前 trusting.
- Code Diff
Compare best-练习 code 使用常见 anti-模式.
常见错误
错误写法
Using 任何 as 快速 fix for 类型错误
正确做法
任何创建 hole in 你的类型系统. Use unknown for untrusted 数据 and proper 类型 for 一切 else. 如果你 必须 suppress, use @ts-expect-错误所以它 是可见 and tracked.
错误写法
不 using discriminated unions for 状态 management
正确做法
Model 状态 as discriminated union 使用常见状态字段. 这个制作不可能状态 unrepresentable and ensures exhaustive handling in 切换语句.
错误写法
Duplicating 类型定义相反的 deriving 它们
正确做法
Derive 类型使用 utility 类型 (选取, Omit, 部分) and 从函数 (ReturnType, 参数). 单个源 的 truth keeps 类型 in sync 使用 implementations.
相关资源
相关速查表
- TypeScript Cheatsheet
快速引用 for 所有 TypeScript 语法 and 模式.
练习 TypeScript 最佳实践
2 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。