TypeScript 高级类型是很多开发者的"拦路虎"—— 条件类型、infer、递归类型…… Claude Code 不只能帮你写,更能解释每一行的原理。
Claude Code 在 TypeScript 类型开发中的角色
擅长:
解释复杂类型的工作原理
生成满足需求的类型定义
调试类型错误("Type X is not assignable to Y")
把 JS 代码转换为完整类型化版本
实现标准库工具类型(Partial/ReturnType 等)
局限:
极度复杂的类型体操(TypeScript 类型系统边界)
需要结合具体项目上下文判断
场景一:理解条件类型(Conditional Types)
告诉 Claude Code:
解释这个类型的工作原理,并给出3个使用案例:
type IsString<T> = T extends string ? true : false
Claude Code 讲解 + 延伸:
typescript
// 基础条件类型
type IsString<T> = T extends string ? true : false
type A = IsString<string> // true
type B = IsString<number> // false
// 分布式条件类型(Union 的魔法)
type ToArray<T> = T extends any ? T[] : never
type C = ToArray<string | number>
// 结果:string[] | number[](不是 (string | number)[])
// 解释:联合类型分布到条件类型的每个成员
// 实用案例:提取函数的返回类型
type GetReturn<T> = T extends (...args: any[]) => infer R ? R : never
type D = GetReturn<() => string> // string
type E = GetReturn<(x: number) => boolean> // boolean场景二:infer 关键字深度使用
Prompt:
帮我写一个类型工具:
从嵌套 Promise 中提取最终值的类型
type UnwrapPromise<T> = ???
比如:
UnwrapPromise<Promise<Promise<string>>> 应该返回 string
Claude Code 生成:
typescript
// 递归 infer:解包嵌套 Promise
type UnwrapPromise<T> =
T extends Promise<infer Inner>
? UnwrapPromise<Inner> // 递归继续解包
: T // 不是 Promise 了,返回 T
type A = UnwrapPromise<Promise<string>> // string
type B = UnwrapPromise<Promise<Promise<number>>> // number
type C = UnwrapPromise<string> // string(已经不是 Promise)
// 延伸:提取函数参数类型
type FirstParam<T extends (...args: any[]) => any> =
T extends (first: infer F, ...rest: any[]) => any ? F : never
type D = FirstParam<(a: string, b: number) => void> // string场景三:映射类型(Mapped Types)
Prompt:
帮我实现一个类型工具 DeepReadonly<T>,
让对象的所有嵌套属性都变成 readonly,
包括数组和嵌套对象。
Claude Code 生成:
typescript
type DeepReadonly<T> =
T extends (infer U)[] // 如果是数组
? ReadonlyArray<DeepReadonly<U>>
: T extends object // 如果是对象
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T // 基本类型,直接返回
// 测试
interface Config {
server: {
host: string
ports: number[]
}
features: string[]
}
type ReadonlyConfig = DeepReadonly<Config>
// 等价于:
// {
// readonly server: {
// readonly host: string
// readonly ports: readonly number[]
// }
// readonly features: readonly string[]
// }
const config: ReadonlyConfig = { server: { host: 'localhost', ports: [80] }, features: [] }
config.server.host = 'other' // TS 错误:Cannot assign to 'host' because it is a read-only property场景四:模板字面量类型
Prompt:
帮我写一个类型,自动生成对象所有嵌套路径的字符串联合:
比如 { a: { b: string; c: number }; d: boolean }
应该生成 "a" | "a.b" | "a.c" | "d"
Claude Code 生成:
typescript
type Paths<T, Prefix extends string = ''> = {
[K in keyof T & string]:
| (Prefix extends '' ? K : `${Prefix}.${K}`)
| (T[K] extends object
? Paths<T[K], Prefix extends '' ? K : `${Prefix}.${K}`>
: never)
}[keyof T & string]
type MyObj = { a: { b: string; c: number }; d: boolean }
type AllPaths = Paths<MyObj>
// "a" | "d" | "a.b" | "a.c"
// 实用场景:类型安全的深层对象访问
function getByPath<T, P extends Paths<T>>(obj: T, path: P) {
// 实现深层访问...
}场景五:Discriminated Union(辨别联合)
Prompt:
我有一个 API 响应类型,成功和失败的结构不同,
帮我用 Discriminated Union 设计,
让 TypeScript 能正确收窄类型。
typescript
type ApiResponse<T> =
| { status: 'success'; data: T; timestamp: number }
| { status: 'error'; code: number; message: string }
function handleResponse<T>(response: ApiResponse<T>) {
if (response.status === 'success') {
// TypeScript 知道这里是成功分支
console.log(response.data) // ✅ data 存在
// console.log(response.code) // ❌ TS 错误:code 不存在
} else {
// TypeScript 知道这里是错误分支
console.log(response.message) // ✅ message 存在
// console.log(response.data) // ❌ TS 错误:data 不存在
}
}常见类型错误修复 Prompt
[类型不兼容]
TypeScript 报错:
"Type '{ name: string }' is not assignable to type 'User'"
相关代码:[粘贴代码]
帮我找出类型不匹配的原因并修复。
[any 泛滥]
帮我把这个到处用 any 的 TypeScript 文件
重构为完全类型安全的版本:
[粘贴文件]
[类型推导失败]
TypeScript 无法正确推导这个泛型函数的返回类型,
帮我添加显式类型标注:
[粘贴函数代码]
来源:TypeScript 官方文档 + Anthropic Claude Code 文档