TypeScript 中的内置工具类型(Utility Type)
📌 点赞收藏关注不迷路!
TypeScript 为我们提供了非常多 内置的工具类型(Utility Types),让我们在处理对象、联合类型、函数签名时更优雅、更高效。
但是这些工具类型名称看上去有些"玄学"------Partial
、Omit
、Pick
、ReturnType
、Extract
......你是不是也有点傻傻分不清?
今天我们就来由浅入深,一口气讲清楚 TS 最常用的 Utility Types,并结合实际示例告诉你什么时候用、为什么好用、怎么用最妙!
🧭 一、什么是 Utility Type?
Utility Type 是 TypeScript 提供的内置泛型类型,用于在已有类型的基础上快速创建新类型。
💡 类似于 JavaScript 的工具函数(如 map()
、filter()
),这些类型是对类型的"加工"操作。
🛠️ 二、对象类 Utility Types(最常用)
1️⃣ Partial<T>
--- 把所有属性变成可选的
ts
type User = { name: string; age: number }
type PartialUser = Partial<User>
// => { name?: string; age?: number }
📌 适用场景:表单更新、Patch 请求、不完整数据对象。
2️⃣ Required<T>
--- 把所有属性变成必填
ts
type OptionalUser = { name?: string; age?: number }
type FullUser = Required<OptionalUser>
// => { name: string; age: number }
📌 适用场景:类型补全,防止使用时忘记字段。
3️⃣ Readonly<T>
--- 所有属性变为只读
ts
type Config = { baseUrl: string }
const readonlyConfig: Readonly<Config> = { baseUrl: '/api' }
readonlyConfig.baseUrl = '/new' // ❌ 报错
📌 适用场景:保护配置对象、防止被修改。
4️⃣ Pick<T, K>
--- 从对象中"挑出"某些属性
ts
type User = { name: string; age: number; email: string }
type PublicUser = Pick<User, 'name' | 'email'>
// => { name: string; email: string }
📌 适用场景:从完整对象中筛选用于展示或传输的字段。
5️⃣ Omit<T, K>
--- 从对象中"排除"某些属性
ts
type InternalUser = Omit<User, 'email'>
// => { name: string; age: number }
📌 适用场景:隐藏敏感字段、不需要的属性。
🧬 三、函数和类型操作类 Utility Types
6️⃣ ReturnType<T>
--- 获取函数返回值类型
ts
function getUser() {
return { name: 'Jin', age: 20 }
}
type User = ReturnType<typeof getUser>
// => { name: string; age: number }
📌 适用场景:接口抽取、避免重复声明返回类型。
7️⃣ Parameters<T>
--- 获取函数的参数类型元组
ts
function add(a: number, b: number): number {
return a + b
}
type Args = Parameters<typeof add>
// => [number, number]
📌 适用场景:将参数传递给另一个函数时保持一致。
8️⃣ ConstructorParameters<T>
--- 构造函数参数类型
ts
class Person {
constructor(public name: string, public age: number) {}
}
type PersonArgs = ConstructorParameters<typeof Person>
// => [string, number]
📌 适用场景:动态实例化类时推导构造函数参数类型。
9️⃣ InstanceType<T>
--- 获取构造函数返回的实例类型
ts
type PersonInstance = InstanceType<typeof Person>
// => Person
📌 适用场景:统一管理工厂函数或类实例的类型。
🔎 四、联合类型相关 Utility Types
🔟 Exclude<T, U>
--- 从 T 中排除可分配给 U 的类型
ts
type Status = 'success' | 'error' | 'loading'
type WithoutLoading = Exclude<Status, 'loading'>
// => 'success' | 'error'
📌 适用场景:过滤掉某些不需要的值或状态。
1️⃣1️⃣ Extract<T, U>
--- 从 T 中提取可分配给 U 的类型
ts
type Result = Extract<Status, 'success' | 'error'>
// => 'success' | 'error'
📌 适用场景:精确匹配子集类型。
1️⃣2️⃣ NonNullable<T>
--- 去除 null 和 undefined
ts
type Value = string | null | undefined
type CleanValue = NonNullable<Value>
// => string
📌 适用场景:表单值处理、接口响应数据约束。
🧠 五、实际开发中组合使用示例
✅ 表单类型处理(结合 Pick + Partial)
ts
type User = { id: string; name: string; age: number; email: string }
type UserForm = Partial<Pick<User, 'name' | 'age' | 'email'>>
// => 可选的 name, age, email 字段(id 被排除)
✅ 接口安全返回(ReturnType + Readonly)
ts
function getConfig() {
return { baseUrl: '/api', retry: 3 }
}
type Config = Readonly<ReturnType<typeof getConfig>>
// 所有字段只读,防止被修改
✅ 函数封装参数提取(Parameters)
ts
function apiLogin(username: string, password: string) {}
const loginArgs: Parameters<typeof apiLogin> = ['user', 'pass']
🎯 六、总结:Utility Types 是类型系统的瑞士军刀
类型 | 作用 |
---|---|
Partial |
所有字段变为可选 |
Required |
所有字段变为必填 |
Readonly |
所有字段只读 |
Pick / Omit |
选择/排除字段 |
ReturnType |
推导函数返回类型 |
Parameters |
推导函数参数类型 |
Exclude / Extract |
类型集合筛选 |
NonNullable |
去除 null/undefined |
它们让类型更灵活、逻辑更清晰、代码更安全,是 TypeScript 高阶开发的基石。
✅ 最后说一句
如果你读完后觉得 Utility Types 没那么神秘了,别忘了给我一个 点赞 + 收藏 + 关注 啊,别等你用的时候再来找这篇文章!
下一篇我可以写:
🧠《10 个你项目里可能漏掉的 TypeScript 技巧》
欢迎留言、发标题,我来继续帮你写教程文!