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 的常见内置工具类型及其应用,适合直接用于项目开发或学习笔记。

相关推荐
已读不回1435 小时前
实现 TypeScript 内置工具类型(源码解析与实现)
typescript
YaeZed5 小时前
TypeScript6(class类)
前端·typescript
漂流瓶jz14 小时前
解锁Babel核心功能:从转义语法到插件开发
前端·javascript·typescript
一支鱼17 小时前
leetcode-6-正则表达式匹配
算法·leetcode·typescript
拜无忧21 小时前
【教程】vue+vite+ts创建一个最新的高性能后台项目架构
vue.js·typescript·vite
GDAL1 天前
解决 ES 模块与 CommonJS 模块互操作性的关键开关esModuleInterop
typescript
Sui_Network2 天前
Yotta Labs 选择 Walrus 作为去中心化 AI 存储与工作流管理的专用数据层
大数据·javascript·人工智能·typescript·去中心化·区块链
一支鱼2 天前
leetcode-5-最长回文子串
算法·leetcode·typescript
定栓2 天前
vue3入门- script setup详解下
前端·vue.js·typescript