ts类型工具

TypeScript 提供了一套强大的内置工具类型(Utility Types),用于从已有类型中派生出新类型,从而提升代码的健壮性、可维护性和开发效率。这些工具类型就像"类型世界的高阶函数",能对类型进行组合、裁剪、转换等操作。


🧰 常用 TypeScript 工具类型速查表

分类 工具类型 作用
基础修饰 Partial<T> T 的所有属性变为可选
Required<T> T 的所有属性变为必填 (移除 ?
Readonly<T> T 的所有属性变为只读
结构挑选 Pick<T, K> T选取 指定键 K 的属性
Omit<T, K> T剔除 指定键 K 的属性
Record<K, T> 构造一个键为 K、值为 T 的对象类型
类型过滤 Exclude<T, U> 从联合类型 T排除 可赋值给 U 的类型
Extract<T, U> 从联合类型 T提取 可赋值给 U 的类型
NonNullable<T> T 中移除 nullundefined
函数相关 ReturnType<T> 获取函数 T返回值类型
Parameters<T> 获取函数 T参数类型元组
ConstructorParameters<T> 获取构造函数的参数类型
InstanceType<T> 获取构造函数的实例类型
ThisParameterType<T> / OmitThisParameter<T> 处理函数中的 this 参数

🔍 典型示例与应用场景

1. Partial<T>:局部更新

ts 复制代码
interface User {
  id: number;
  name: string;
  email: string;
}

// 所有字段变为可选
type UpdateUser = Partial<User>;

function updateUser(id: number, changes: UpdateUser) {
  // 只需传入要修改的字段
}
updateUser(1, { name: "Alice" }); // ✅

2. Pick<T, K> / Omit<T, K>:按需选择或排除字段

ts 复制代码
type UserPreview = Pick<User, 'id' | 'name'>; // { id: number; name: string }
type UserWithoutId = Omit<User, 'id'>;        // { name: string; email: string }

3. Record<K, T>:构建配置对象

ts 复制代码
type Theme = 'light' | 'dark';
type ColorMap = Record<Theme, string>; // { light: string; dark: string }

4. ReturnType<T>:推导函数返回类型

ts 复制代码
function fetchUser() {
  return { id: 1, name: "Bob" };
}

type User = ReturnType<typeof fetchUser>; // { id: number; name: string }

5. Exclude<T, U> / Extract<T, U>

ts 复制代码
type Status = 'loading' | 'success' | 'error';
type ValidStatus = Exclude<Status, 'loading'>; // 'success' | 'error'
type LoadingOnly = Extract<Status, 'loading'>; // 'loading'

💡 小贴士

  • 这些工具类型基于 映射类型(Mapped Types)条件类型(Conditional Types)infer 等高级特性实现。

  • 它们是不可变的:不会修改原始类型,而是生成一个新类型。

  • 组合使用 ,例如:

    ts 复制代码
    type SafeUser = Readonly<Partial<User>>;

如需深入某个工具类型的源码实现或更多实战案例,可以告诉我具体类型(如 OmitReturnType),我可以进一步详解!

相关推荐
We་ct7 小时前
LeetCode 54. 螺旋矩阵:两种解法吃透顺时针遍历逻辑
前端·算法·leetcode·矩阵·typescript
We་ct8 小时前
LeetCode 36. 有效的数独:Set实现哈希表最优解
前端·算法·leetcode·typescript·散列表
Async Cipher1 天前
TypeScript 的用法
前端·typescript
We་ct1 天前
LeetCode 30. 串联所有单词的子串:从暴力到高效,滑动窗口优化详解
前端·算法·leetcode·typescript
刘联其2 天前
封装一个完整的HttpClient.ts
前端·javascript·typescript
走粥2 天前
TypeScript 泛型
开发语言·前端·javascript·windows·typescript
阿蒙Amon2 天前
TypeScript学习-第3章:复合类型
javascript·学习·typescript
踢球的打工仔2 天前
typescript-接口的基本使用(三)
前端·javascript·typescript
EndingCoder2 天前
TypeScript 最新特性:跟踪版本更新
开发语言·前端·javascript·typescript
止观止2 天前
重新认识 TypeScript:不仅仅是“带类型的 JS”
javascript·typescript