TypeScript 内置工具类型大全(ReturnType、Omit、Pick 等)

目标读者:掌握了 TypeScript 基础语法,想在业务中更高效地使用内置工具类型的前端/全栈开发者。


目录

  1. 什么是工具类型

  2. 常用工具类型分类

    • 基础修饰类(Partial、Required、Readonly)
    • 结构挑选类(Pick、Omit、Record)
    • 类型过滤类(Exclude、Extract、NonNullable)
    • 函数相关类(ReturnType、Parameters、ConstructorParameters、InstanceType、ThisParameterType、OmitThisParameter)
  3. 实际业务场景示例

  4. 总结与学习建议


1. 什么是工具类型

TypeScript 提供了一些 内置的泛型类型 ,用来简化常见的类型操作,我们称之为 工具类型(Utility Types)

它们大多数基于 条件类型infer映射类型 实现,可以帮助我们减少样板代码,让类型定义更灵活。


2. 常用工具类型分类

2.1 基础修饰类

Partial<T>

  • 作用:将 T 的所有属性变为可选。
ts 复制代码
interface User {
  id: number;
  name: string;
  age: number;
}

type PartialUser = Partial<User>;
// { id?: number; name?: string; age?: number }

应用场景 :更新用户信息的 updateUser 接口参数。

Required<T>

  • 作用:将 T 的所有属性变为必选。
ts 复制代码
interface Config {
  url?: string;
  cache?: boolean;
}

type StrictConfig = Required<Config>;
// { url: string; cache: boolean }

应用场景:校验配置时必须提供所有字段。

Readonly<T>

  • 作用:将 T 的所有属性变为只读。
ts 复制代码
interface Point {
  x: number;
  y: number;
}

type ReadonlyPoint = Readonly<Point>;
// { readonly x: number; readonly y: number }

应用场景 :禁止修改 props,如 React 的 props


2.2 结构挑选类

Pick<T, K>

  • 作用:从 T 中挑选部分属性。
ts 复制代码
interface User {
  id: number;
  name: string;
  age: number;
}

type UserPreview = Pick<User, 'id' | 'name'>;
// { id: number; name: string }

应用场景 :列表页只展示 idname

Omit<T, K>

  • 作用:从 T 中排除某些属性。
ts 复制代码
interface User {
  id: number;
  name: string;
  password: string;
}

type SafeUser = Omit<User, 'password'>;
// { id: number; name: string }

应用场景:对外返回用户信息时隐藏敏感字段。

Record<K, T>

  • 作用:构造一个对象类型,key 来自联合类型,值为指定类型。
ts 复制代码
type Role = 'admin' | 'user';

type RoleMap = Record<Role, number>;
// { admin: number; user: number }

应用场景:角色与权限映射表。


2.3 类型过滤类

Exclude<T, U>

  • 作用:从 T 中排除 U
ts 复制代码
type T = Exclude<'a' | 'b' | 'c', 'a'>;
// 'b' | 'c'

应用场景:过滤掉不需要的类型。

Extract<T, U>

  • 作用:提取 TU 的交集。
ts 复制代码
type T = Extract<'a' | 'b' | 'c', 'a' | 'f'>;
// 'a'

应用场景:提取允许的值类型。

NonNullable<T>

  • 作用:排除 nullundefined
ts 复制代码
type T = NonNullable<string | null | undefined>;
// string

应用场景:在严格模式下消除空值。


2.4 函数相关类

ReturnType<T>

  • 作用:获取函数返回值类型。
ts 复制代码
function fetchUser() {
  return { id: 1, name: 'Alice' };
}

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

应用场景:接口返回值类型提取,避免重复定义。

Parameters<T>

  • 作用:获取函数参数类型。
ts 复制代码
function greet(name: string, age: number) {}

type Params = Parameters<typeof greet>;
// [string, number]

应用场景:复用函数的参数定义。

ConstructorParameters<T>

  • 作用:获取构造函数的参数类型。
ts 复制代码
class Person {
  constructor(name: string, age: number) {}
}

type Params = ConstructorParameters<typeof Person>;
// [string, number]

应用场景:工厂函数自动推导参数类型。

InstanceType<T>

  • 作用:获取构造函数的实例类型。
ts 复制代码
class Person {
  name: string;
  constructor(name: string) { this.name = name; }
}

type P = InstanceType<typeof Person>;
// Person

应用场景:通过类类型生成实例类型。

ThisParameterType<T>

  • 作用:提取函数的 this 类型。
ts 复制代码
function say(this: { name: string }) { return this.name; }

type T = ThisParameterType<typeof say>;
// { name: string }

应用场景:定义函数上下文类型。

OmitThisParameter<T>

  • 作用:移除函数的 this 参数。
ts 复制代码
function say(this: { name: string }) { return this.name; }

type Fn = OmitThisParameter<typeof say>;
// () => string

应用场景 :把绑定 this 的函数转为普通函数。


3. 实际业务场景示例

3.1 API 返回值提取

ts 复制代码
async function getUser() {
  return { id: 1, name: 'Tom', token: 'secret' };
}

type User = Omit<ReturnType<typeof getUser>, 'token'>;
// { id: number; name: string }

3.2 表单更新接口

ts 复制代码
interface UserForm {
  name: string;
  age: number;
  email: string;
}

function updateUser(id: number, data: Partial<UserForm>) {}

3.3 动态映射表

ts 复制代码
type Routes = 'home' | 'about' | 'login';

type RouteConfig = Record<Routes, string>;
// { home: string; about: string; login: string }

3.4 React Props 约束

ts 复制代码
interface ButtonProps {
  label: string;
  onClick: () => void;
  disabled?: boolean;
}

type RequiredButton = Required<ButtonProps>; // 强制所有 props 必须传

4. 总结与学习建议

  • 工具类型大幅减少了重复类型定义,让代码更简洁。

  • 常用的三大类:

    • 修饰:Partial、Required、Readonly
    • 挑选:Pick、Omit、Record
    • 函数:ReturnType、Parameters 等
  • 建议结合业务场景学习,比如 API 类型推导组件 Props 约束权限映射表

  • 进一步学习:可以深入研究工具类型的源码实现,多写一些"类型体操"题目来加深理解。


这篇文章覆盖了 TypeScript 的常见内置工具类型及其应用,适合直接用于项目开发或学习笔记。

相关推荐
VT.馒头8 小时前
【力扣】2625. 扁平化嵌套数组
前端·javascript·算法·leetcode·职场和发展·typescript
San30.11 小时前
从零构建坚固的前端堡垒:TypeScript 与 React 实战深度指南
前端·react.js·typescript
VT.馒头13 小时前
【力扣】2694. 事件发射器
前端·javascript·算法·leetcode·职场和发展·typescript
止观止14 小时前
像三元表达式一样写类型?深入理解 TS 条件类型与 `infer` 推断
前端·typescript
We་ct15 小时前
LeetCode 73. 矩阵置零:原地算法实现与优化解析
前端·算法·leetcode·矩阵·typescript
We་ct15 小时前
LeetCode 48. 旋转图像:原地旋转最优解法
前端·算法·leetcode·typescript
We་ct1 天前
LeetCode 54. 螺旋矩阵:两种解法吃透顺时针遍历逻辑
前端·算法·leetcode·矩阵·typescript
We་ct1 天前
LeetCode 36. 有效的数独:Set实现哈希表最优解
前端·算法·leetcode·typescript·散列表
Async Cipher2 天前
TypeScript 的用法
前端·typescript
We་ct2 天前
LeetCode 30. 串联所有单词的子串:从暴力到高效,滑动窗口优化详解
前端·算法·leetcode·typescript