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

相关推荐
@@@@@@@@542 小时前
JavaScript 的缺点与 TypeScript 的弥补
开发语言·javascript·typescript
用户0934077735143 小时前
HarmonyOS WPS Open SDK 实践:最小打开闭环与 enableEdit 分支处理
typescript·harmonyos
柯克七七21 小时前
我把 bug 修得太干净了,测试组以为这个模块本来就没问题
前端·javascript·typescript
退休倒计时1 天前
【每日一题】LeetCode 39. 组合总和 TypeScript
算法·leetcode·typescript
yyt3630458411 天前
KlineChartQuant Tooltip 高频交互 200FPS 性能优化完整复盘
前端·经验分享·性能优化·typescript·vue·交互·chrome devtools
用户0934077735141 天前
HarmonyOS WPS Open SDK 实践:办公审批附件「打开—编辑—回传」代码实现
typescript·harmonyos
Flynt1 天前
TypeScript 5.8 让我少踩了一个大坑,顺手再聊聊 --erasableSyntaxOnly
前端·javascript·typescript
退休倒计时2 天前
【每日一题】LeetCode 17. 电话号码的字母组合 TypeScript
算法·leetcode·typescript
无情的西瓜皮3 天前
MCP 协议实战:从零搭建一个 MCP 服务器(Node.js 版)
vue.js·人工智能·typescript·node.js
退休倒计时3 天前
【每日一题】LeetCode 78. 子集 TypeScript
算法·leetcode·typescript