第 14 章:最佳实践与速查
最后一章不讲新语法,只回答三个问题:类型该放在哪、什么时候该收手、团队怎么保持一致。
学习目标
- 知道类型文件该按什么维度组织,避免一个
types.ts越滚越大 - 掌握"少断言、多收窄、边界校验"这三条最核心的原则
- 会在接口边界用
zod做运行时校验,并让类型从 schema 推导 - 有一套能在团队里落地的规范清单和自检清单
- 有一张随时能翻的语法速查表
14.1 类型放在哪
反模式:一个巨大的 types.ts
// ❌ 三个月后没人敢动
src/types.ts // 800 行,混着 User、Order、API、表单、组件 props问题是:
- 改一个字段,文件冲突概率高;
- 找类型靠全文搜索,不知道归属;
- 循环依赖风险大(所有模块都 import 它)。
推荐:按"域"分,就近放置
src/
├── api/
│ ├── client.ts # 请求封装
│ └── types.ts # 接口信封、错误结构
├── features/
│ ├── user/
│ │ ├── types.ts # User、UserPatch、UserResponse
│ │ ├── api.ts
│ │ └── components/
│ └── order/
│ ├── types.ts
│ └── api.ts
├── shared/
│ └── types/
│ ├── result.ts # 通用 Result / Pagination
│ └── brand.ts # 品牌类型(可选)
└── components/
└── Button/
└── Button.tsx # props 类型跟组件放在一起三条规则:
| 规则 | 说明 |
|---|---|
| 组件 props 就近放 | 和组件同文件,或同目录的 types.ts,不放进全局 types |
| 业务类型按域放 | features/user/types.ts,谁用谁引 |
真正跨域通用的才放 shared/ | Pagination、Result 这种 |
命名约定
| 后缀 | 含义 |
|---|---|
XxxProps | 组件属性 |
XxxInput | 函数/接口入参 |
XxxResponse | 接口返回 |
XxxPatch / XxxUpdate | 更新用的可选字段版本 |
XxxState | 状态机 / 前端状态 |
XxxConfig | 配置对象 |
命名清楚的价值在于:看到类型名就知道它该在哪一层用,不用跳过去看定义。
14.2 七条核心原则
一、类型描述现实,不是描述愿望
// ❌ 接口实际可能返回 null,但类型写死了 string
interface UserResponse { name: string }
// ✅ 如实描述
interface UserResponse { name: string | null }类型写得"好看",只会把问题推到运行时。宁可类型难看一点,也要和真实数据一致。
二、外部数据一律 unknown 起步
const raw: unknown = await res.json()不要一上来 as User。unknown 会强迫你做检查,这是唯一能真正防住脏数据的方式。
三、能用收窄就不用断言
// ❌
const user = data as User
// ✅
if (isUser(data)) {
const user = data
}断言的错误编译器发现不了;收窄的错误在写的时候就会暴露(守卫写错了,测试一跑就现原形)。
四、边界只校验一次,往里全是类型
// 边界(api/client.ts)
const user = UserSchema.parse(json) // 这里校验
// 内部(业务代码)
function renderUser(user: User) { ... } // 这里完全信任类型不要在业务代码里到处 if (user.name) 判空——如果边界校验过了,内部就该是干净的。反复防御说明边界没做好。
五、一个概念一个类型
// ❌ 同一个 User 在三处各写一遍,改一处漏两处
// ✅ 定义一次,用 Pick / Omit / Partial 派生
interface User { id: string; name: string; email: string }
type PublicUser = Omit<User, 'email'>六、类型不要跨层泄漏
接口 DTO 不要直接当组件 props 用:
// ❌ 后端加个字段,组件就被动受影响
function Card({ user }: { user: ApiUser }) {}
// ✅ 组件声明自己需要什么
function Card({ name, avatar }: { name: string; avatar?: string }) {}组件只依赖它真正用到的字段,接口变化不会波及 UI。
七、先让编译器帮忙,再动手改
改类型定义 → 看报错列表 → 逐个修。这是第 13 章讲过的顺序,也是最省事的重构方式。
14.3 边界校验:zod 的最小用法
先明确"边界"在哪——它是整个系统里唯一需要运行时校验的地方:
npm install zodimport { z } from 'zod'
const UserSchema = z.object({
id: z.string(),
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().positive().optional()
})
// 从 schema 推导类型,永不漂移
type User = z.infer<typeof UserSchema>两种校验方式
// 抛错式:校验失败直接抛 ZodError
const user = UserSchema.parse(json)
// 结果式:不抛错,返回 { success, data | error }
const result = UserSchema.safeParse(json)
if (!result.success) {
console.error(result.error.issues)
return
}
const user = result.data处理接口响应时更推荐 safeParse,方便把错误转成用户能看懂的提示。
常见 schema 片段
const PaginationSchema = z.object({
page: z.number().int().min(1),
pageSize: z.number().int().min(1).max(100),
total: z.number().int().nonnegative()
})
const ApiResponseSchema = <T extends z.ZodTypeAny>(data: T) =>
z.object({
code: z.number(),
message: z.string(),
data
})
const UserListSchema = ApiResponseSchema(z.array(UserSchema))
type UserList = z.infer<typeof UserListSchema>schema 和类型是一体的:校验规则改了,类型自动跟着改,不会出现"类型说是 string,实际校验是 number"这种错位。
什么时候用、什么时候不用
| 用 | 不用 |
|---|---|
| 接口响应、请求体 | 纯内部函数之间传值 |
| 表单输入 | 编译期就能确定的常量 |
localStorage / URL 参数 / 环境变量 | 已经校验过的数据再往下传 |
| 第三方 webhook 回调 | — |
14.4 前后端类型共享
三种常见方案:
| 方案 | 做法 | 适用 |
|---|---|---|
| 代码生成 | 从 OpenAPI / Protobuf 生成类型 | 后端接口稳定、团队有规范 |
| 共享包 | monorepo 里 packages/shared-types | 前后端同一个仓库 |
| schema 共享 | 后端用 zod 定义,前端直接引 schema | 同一套 TS 技术栈 |
最稳的是第一种:类型是生成的,不是手抄的,永远不会漂移。
如果只能手写,至少守住一条:接口字段的命名、可选性、null 语义,前后端要对齐一次并写进文档。这三种不一致最常见:
// 后端:字段可能不返回
{ name?: string }
// 前端以为是必填
interface User { name: string } // 运行时 undefined
// 或者:后端返回 null,前端以为是"没有这个字段"
{ name: null }?、| null、| undefined 三者语义不同,联调时最容易在这里扯皮。
14.5 any 与 Lint 配置
一份可以直接抄的 ESLint 配置片段(@typescript-eslint):
{
"rules": {
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
"@typescript-eslint/consistent-type-imports": "error",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/switch-exhaustiveness-check": "error"
}
}逐条说明:
| 规则 | 作用 |
|---|---|
no-explicit-any | 禁止手写 any,逼你用 unknown 或具体类型 |
consistent-type-imports | 自动把类型导入改成 import type |
no-non-null-assertion | 提醒 ! 用得太多(设 warn 比 error 现实) |
switch-exhaustiveness-check | 联合类型的 switch 漏分支直接报错,等于自动版 assertNever |
老项目一次性全开不现实,建议顺序:
- 先开
consistent-type-imports(自动修复,零成本); - 再开
switch-exhaustiveness-check(能抓真 bug); no-explicit-any先设warn,统计数量,按目录逐步清零;- 最后把
tsconfig的strict补齐。
14.6 团队规范清单
可以直接贴进 CONTRIBUTING.md:
## TypeScript 规范
### 类型定义
- [ ] 对象用 interface,联合/元组/工具类型用 type,同一项目保持统一
- [ ] 导出的函数标注返回类型,内部小函数可省
- [ ] 组件 props 与组件同目录,不放进全局 types
- [ ] 业务类型按 feature 分目录,跨域通用的才放 shared/
### 类型使用
- [ ] 禁止 `any`;不确定用 `unknown` 并收窄
- [ ] 优先类型守卫(`is` / `asserts`),少用 `as`
- [ ] 禁止非空断言 `!`,除非注释说明为什么一定非空
- [ ] 联合类型用判别式字段,不用"多个可选字段"表达状态
### 边界
- [ ] 接口响应、表单、localStorage 必须运行时校验(zod)
- [ ] 类型从 schema 推导,不手写两份
- [ ] 禁止把接口 DTO 直接当组件 props
### 配置
- [ ] `strict: true`
- [ ] `noUncheckedIndexedAccess: true`(新项目)
- [ ] 提交前跑 `tsc --noEmit` 和 lint14.7 速查表
类型写法
| 需求 | 写法 |
|---|---|
| 联合 | string | number |
| 交叉 | A & B |
| 字面量 | 'pending' | 'paid' |
| 数组 | string[] / Array<string> |
| 只读数组 | readonly string[] |
| 元组 | [string, number] |
| 可选属性 | { name?: string } |
| 只读属性 | { readonly id: string } |
| 索引签名 | { [key: string]: number } |
| 函数类型 | (a: number) => string |
| 泛型函数 | <T>(x: T) => T |
| 泛型约束 | <T extends { id: string }> |
| 默认类型参数 | <T = unknown> |
| 类型谓词 | (v: unknown): v is User |
| 断言函数 | (v: unknown): asserts v is User |
| 键的联合 | keyof T |
| 值的联合 | T[keyof T] |
| 元素类型 | T[number] |
| 从值取类型 | typeof value |
| 映射类型 | { [K in keyof T]: T[K] } |
内置工具类型
| 类型 | 作用 |
|---|---|
Partial<T> | 全部可选 |
Required<T> | 全部必填 |
Readonly<T> | 全部只读 |
Pick<T, K> | 挑出键 K |
Omit<T, K> | 去掉键 K |
Record<K, V> | 键 K 值 V 的对象 |
Exclude<T, U> | 从联合中排除 U |
Extract<T, U> | 从联合中只留 U |
NonNullable<T> | 去掉 null / undefined |
ReturnType<F> | 函数返回类型 |
Parameters<F> | 函数参数元组 |
Awaited<T> | Promise 解析后的类型 |
类型收窄
| 手段 | 写法 |
|---|---|
typeof | if (typeof v === 'string') |
in | if ('permissions' in user) |
instanceof | if (err instanceof Error) |
| 判别式 | if (result.ok) / switch (state.status) |
| 真值 | if (name) |
| 相等 | if (mode === 'a') |
| 自定义守卫 | if (isUser(v)) |
| 断言函数 | assertIsString(v) |
| 数组过滤 | arr.filter((x): x is string => x !== null) |
| 穷尽检查 | default: return assertNever(x) |
空值处理
| 写法 | 含义 |
|---|---|
a?.b | 链路上有空就返回 undefined |
a ?? b | 左边是 null/undefined 才取右边 |
a || b | 左边是假值就取右边(会吃掉 0、'') |
a != null | 同时排除 null 和 undefined |
高频报错对照
| 报错 | 先查什么 |
|---|---|
Type 'X' is not assignable to type 'Y' | 哪边类型错了:改数据还是改类型 |
is possibly 'null' or 'undefined' | 源头是否该保证非空 |
Property 'x' does not exist on type 'Y' | 类型定义是否过时 / 是否要收窄 |
Object literal may only specify known properties | 报错末尾指出多余字段名 |
can't be used to index type 'Y' | 键有限用 keyof,无限用 Record |
Cannot find module 'x' | 包装了吗 / @types 装了吗 / 别名配了吗 |
Two types have separate declarations | 依赖重复,npm ls 查 |
14.8 提交前自检清单
新写一个 TS 文件,或者改完一个功能,问自己六句:
- 有没有
any?能不能换成unknown或具体类型? - 有没有
as?能不能换成类型守卫? - 有没有
!?能不能在源头保证非空? - 外部数据(接口、表单、storage)校验了吗?
- 导出的函数标返回类型了吗?
npx tsc --noEmit和 lint 都过了吗?
六条都过,这份代码三个月后还看得懂。
14.9 下一步学什么
这门课停在"能读懂、能写对"。往下有三个方向,按需选:
| 方向 | 学什么 | 适合 |
|---|---|---|
| 前端框架 | React / Vue 的类型写法(泛型组件、ComponentProps、hooks 类型) | 要写前端 |
| Node 工程 | NestJS / Fastify 的装饰器与 DI 类型、Prisma 生成类型 | 要做后端服务 |
| 运行时校验 | zod / valibot 深入、OpenAPI 代码生成 | 要把接口做扎实 |
但在学下一个框架之前,先把这本书里的三件事用熟:收窄、泛型、边界校验。这三个是跨框架通用的,其余都是具体生态的语法糖。
本章小结
| 要点 | 说明 |
|---|---|
| 类型组织 | 按 feature 分目录;props 就近放;通用类型才进 shared/ |
| 核心原则 | 描述现实、外部 unknown、少断言、边界只校验一次、概念一个类型 |
| 边界校验 | zod 一份 schema 同时产出校验与类型 |
| 类型共享 | 优先代码生成,其次共享包,最后手写对齐 |
| Lint | 先开自动修复类规则,no-explicit-any 逐步收紧 |
| 速查表 | 类型写法、工具类型、收窄手段、空值处理、报错对照 |
| 自检 | 六问:any、as、!、校验、返回类型、tsc --noEmit |
| 下一步 | 收窄 + 泛型 + 边界校验先练熟,再挑框架 |
到这里,14 章走完了。回头看第 1 章那句"类型不是写给编译器看的,是写给三个月后的自己看的"——现在应该能体会到了。
有问题欢迎回到任意一章查,每一章的「本章小结」都是那一章的最短路径。