341 字
1 分钟
TypeScript 类型系统常见报错与解决
TypeScript 的类型系统在实际使用中会遇到不少报错,这里整理一些常见的。
1. 对象可能为 undefined
这是 TS 最常见的报错,没有之一:
const user = getUser() // User | undefined
console.log(user.name) // 对象可能为 "undefined"解决方案:
// 方式一:可选链(推荐)console.log(user?.name)
// 方式二:非空断言(你确定它不是 undefined 时)console.log(user!.name)
// 方式三:类型守卫if (user) { console.log(user.name) // 这里 TS 知道 user 不是 undefined}踩坑点: ! 非空断言只是告诉 TS “相信我”,运行时该报错还是会报错。优先用 ?. 或类型守卫。
2. 联合类型只能访问公共属性
type Fish = { swim: () => void }type Bird = { fly: () => void }
function move(animal: Fish | Bird) { animal.swim() // 类型 "Bird" 上不存在属性 "swim"}解决方案:类型收窄
function move(animal: Fish | Bird) { if ('swim' in animal) { animal.swim() // TS 知道这里是 Fish } else { animal.fly() // TS 知道这里是 Bird }}或者用 discriminated union(可辨识联合):
type Shape = | { kind: 'circle'; radius: number } | { kind: 'rect'; width: number; height: number }
function area(shape: Shape) { switch (shape.kind) { case 'circle': return Math.PI * shape.radius ** 2 case 'rect': return shape.width * shape.height }}3. 数组解构的类型推断
const arr = [1, 'hello', true]const [a, b, c] = arr
// a 的类型是 string | number | boolean// 不是 1, 'hello', true想要元组类型:
const arr: [number, string, boolean] = [1, 'hello', true]const [a, b, c] = arr// a: number, b: string, c: boolean
// 或者用 as constconst arr = [1, 'hello', true] as const// 类型是 readonly [1, "hello", true]4. Record 和 Map 的区别
// key 只能是 string | number | symbolconst map: Record<string, number> = {}map[123] = 1 // number 会被转成 stringmap[true] = 1 // 不能用 boolean 做 key
// 想用任意类型做 key,用 Mapconst map = new Map<boolean, number>()map.set(true, 1) //踩坑场景: 用对象做 key 的时候:
const cache: Record<???, any> = {} // 对象不能做 key
// 用 Mapconst cache = new Map<object, any>()const obj = { id: 1 }cache.set(obj, 'data')5. 函数重载
// 这不是重载,是联合类型function add(a: number | string, b: number | string): number | string { if (typeof a === 'number' && typeof b === 'number') { return a + b } return `${a}${b}`}
add(1, 2) // 返回类型是 number | string,不精确正确的函数重载:
function add(a: number, b: number): numberfunction add(a: string, b: string): stringfunction add(a: number | string, b: number | string): number | string { if (typeof a === 'number' && typeof b === 'number') { return a + b } return `${a}${b}`}
add(1, 2) // 返回类型是 numberadd('a', 'b') // 返回类型是 string6. 泛型约束
// 泛型默认是 unknown,不能访问属性function getLength<T>(item: T): number { return item.length // 类型 "T" 上不存在属性 "length"}
// 加约束function getLength<T extends { length: number }>(item: T): number { return item.length //}
getLength('hello') //getLength([1, 2]) //getLength(123) // number 没有 length 属性7. keyof 和 typeof 的组合
const config = { host: 'localhost', port: 3000, debug: true}
// 想让参数只能是 config 的 keyfunction getConfig(key: string) { return config[key] // 报错:元素隐式具有 "any" 类型}
// 用 keyoffunction getConfig(key: keyof typeof config) { return config[key] // 类型安全}
getConfig('host') //getConfig('xxx') // 编译报错8. 类型断言 vs 类型守卫
// 类型断言:告诉 TS "相信我"const el = document.getElementById('app') as HTMLDivElementel.style.color = 'red' // 编译通过,但运行时可能出错
// 类型守卫:运行时真正检查function isDivElement(el: HTMLElement): el is HTMLDivElement { return el instanceof HTMLDivElement}
const el = document.getElementById('app')if (isDivElement(el)) { el.style.color = 'red' // 类型安全}原则: 能用类型守卫就不用断言。
9. never 类型的妙用
// 穷尽检查type Status = 'pending' | 'success' | 'error'
function handleStatus(status: Status) { switch (status) { case 'pending': return '加载中' case 'success': return '成功' case 'error': return '失败' default: const _: never = status // 如果漏了 case,这里会报错 return _ }}
// 如果后来加了 'idle' 状态,不处理 default 会报编译错误10. satisfies 操作符(TS 4.9+)
type Theme = { primary: string bg: string}
// as 会丢失类型信息const theme = { primary: '#1890ff', bg: '#fff', fontSize: 14} as Theme // fontSize 没被检查,还能访问到
// satisfies 既检查类型,又保留精确类型const theme = { primary: '#1890ff', bg: '#fff', fontSize: 14 // 报错:不在 Theme 类型中} satisfies Themesatisfies 是 as 的更好替代品,推荐在新项目中使用。
总结
TypeScript 类型系统的核心:
- 编译期发现错误,减少运行时 bug
- 类型本身就是文档,看签名就知道用法
- 不需要一开始就写完美类型,逐步收紧就行
实际项目中,先 any 跑起来,再慢慢补类型,是比较务实的做法。
分享
如果这篇文章对你有帮助,欢迎分享给更多人!
TypeScript 类型系统常见报错与解决
https://www.403bug.top/posts/typescript-pitfalls/ 部分信息可能已经过时
相关文章 智能推荐





