TypeScript 在业务项目中的落地姿势
MrSmy Lv5

TypeScript 4.5 在这一年发布,前端项目上 TS 基本成了默认选项。但”用了 TS”和”用好 TS”是两件事——很多项目里 any 满天飞,tsconfig 是脚手架默认值,类型检查排在 CI 最后,红灯了直接跳过。这篇整理我们踩过之后留下来的实践。

tsconfig 的几个关键项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"compilerOptions": {
"target": "ES2019",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"exactOptionalPropertyTypes": false,
"skipLibCheck": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": { "@/*": ["src/*"] }
},
"include": ["src/**/*.ts", "src/**/*.vue"]
}
  • strict: true 一次性打开 strictNullChecks、noImplicitAny 等一组开关。老项目可以先开 strictNullChecks 这一项,它带来的类型安全收益最大
  • skipLibCheck: true 跳过 node_modules 里 .d.ts 的检查,能省下大量编译时间,副作用极小
  • paths 一定要和构建工具的 alias 保持一致,否则 TS 认,打包不认(或者反过来)

类型守卫:比 as 更值钱

业务里最常遇到的是”联合类型收窄”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface OrderPaid {
status: 'paid'
paidAt: string
amount: number
}

interface OrderRefunded {
status: 'refunded'
refundedAt: string
reason: string
}

type Order = OrderPaid | OrderRefunded

function getLabel(order: Order) {
if (order.status === 'paid') {
// 这里 order 自动收窄为 OrderPaid
return `${order.amount} 元,付款于 ${order.paidAt}`
}
return `已退款:${order.reason}`
}

用字面量做 status 的类型,比 enum 更灵活,也能让后端 JSON 直接对上。

自定义守卫用于复杂场景:

1
2
3
4
5
6
7
8
function isPaid(order: Order): order is OrderPaid {
return order.status === 'paid'
}

// 断言函数
function assertDefined<T>(val: T | undefined | null, msg: string): asserts val is T {
if (val == null) throw new Error(msg)
}

as 是”我保证”,is 是”运行时验证过”。前者骗编译器,后者保护运行时。业务代码里 as 出现超过三行的地方,基本都值得改成守卫函数。

泛型的正确用法

泛型不是越抽象越好。业务里真正有用的只有几种:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 1. 统一接口返回结构
interface ApiResponse<T> {
code: number
message: string
data: T
}

async function request<T>(url: string): Promise<ApiResponse<T>> {
const res = await fetch(url)
return res.json()
}

const { data } = await request<{ id: number; name: string }>('/api/user')

// 2. 约束字段名
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
return keys.reduce((acc, key) => {
acc[key] = obj[key]
return acc
}, {} as Pick<T, K>)
}

K extends keyof T 这个约束是泛型最实用的形态:传错字段名直接编译报错。

常见坑

1. any 会传染

1
2
const res = await fetch('/api') as any
const user = res.data.user // 这里全是 any,后面全丢类型

一个 any 往下传两层,整条链路的类型检查就失效了。要么补接口类型,要么用 unknown + 守卫,后者会强制你在用之前做判断。

2. 数组的 includes 报错

1
2
3
4
5
const list = ['a', 'b'] as const
list.includes('c') // 报错:参数类型不匹配

const list2: string[] = ['a', 'b']
list2.includes('c') // 正常

as const 会把类型收窄成字面量元组,includes 的参数就被限制住了。需要时显式宽化:(list as readonly string[]).includes('c')。

3. 枚举的坑

数字枚举是”双向映射”,运行时会产生额外的对象,和 const enum 在 isolatedModules 下又冲突。业务上我基本不用 enum,统一用 as const 对象 + 联合类型:

1
2
3
4
5
6
7
export const OrderStatus = {
Pending: 'pending',
Paid: 'paid',
Refunded: 'refunded'
} as const

export type OrderStatus = typeof OrderStatus[keyof typeof OrderStatus]

4. 第三方库没有类型

1
2
3
4
// src/types/legacy-lib.d.ts
declare module 'legacy-lib' {
export function format(input: string, opts?: { precision?: number }): string
}

先自己写最小声明,比直接 // @ts-ignore 好得多。@ts-ignore 会屏蔽掉真正的问题,建议改成 // @ts-expect-error,它有”错误消失后反而报错”的特性,能提醒你及时清理。

5. 类型只在编译期

1
import type { User } from './types'   // 只在类型位置使用,不产生运行时代码

TS 4.5 之后 import type 很重要,能避免打包器把只用于类型的导入当真实依赖保留下来。

迁移策略

给老项目上 TS,我们按这个顺序:

  1. 先把构建链路的 ts-loader / babel-preset-typescript 接好,允许 .js 存在
  2. 新文件一律 .ts,老文件只在改动时重命名
  3. 全局 allowJs: true、checkJs: false,先不检查 JS
  4. 从工具函数和 API 层开始补类型——它们复用率高,收效最快
  5. 最后开 strict,逐个模块消灭报错

不要一开始就全量 strict,几千个报错会让人直接放弃。真正的收益也不在”有多少类型”,而在关键数据流(接口响应、状态管理、表单)上有没有类型保护。

小结

TS 的价值不是消灭运行时错误,而是让”改名、加字段、删字段”这些改动在编译期就暴露影响面。所以判断一个项目 TS 用得好不好,看一个指标就够了:改一个接口字段,需要手动搜索多少处。

  • 本文标题:TypeScript 在业务项目中的落地姿势
  • 本文作者:MrSmy
  • 创建时间:2021-12-05 16:38:00
  • 本文链接:https://fengyang.live/2021/12/05/TypeScript在业务项目中的落地姿势/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!