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),我可以进一步详解!

相关推荐
程序猿阿伟3 小时前
《TypeScript中Protobuf到运行时类型安全的转换指南》
javascript·安全·typescript
We་ct3 小时前
LeetCode 228. 汇总区间:解题思路+代码详解
前端·算法·leetcode·typescript
阿蒙Amon12 小时前
TypeScript学习-第10章:模块与命名空间
学习·ubuntu·typescript
VT.馒头17 小时前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
AAA阿giao1 天前
从零拆解一个 React + TypeScript 的 TodoList:模块化、数据流与工程实践
前端·react.js·ui·typescript·前端框架
hedley(●'◡'●)1 天前
基于cesium和vue的大疆司空模仿程序
前端·javascript·vue.js·python·typescript·无人机
百锦再1 天前
Vue高阶知识:利用 defineModel 特性开发搜索组件组合
前端·vue.js·学习·flutter·typescript·前端框架
小杨同学呀呀呀呀1 天前
Ant Design Vue <a-timeline>时间轴组件失效解决方案
前端·javascript·vue.js·typescript·anti-design-vue
VT.馒头2 天前
【力扣】2721. 并行执行异步函数
前端·javascript·算法·leetcode·typescript
guangzan2 天前
为博客园注入现代 UI 体验:shadcn 皮肤上线
typescript·tailwindcss·shadcn ui·tona