TS内置工具类之Partial、Required、Pick、Record、Readonly、Omit

TS项目开发中,或多或少会遇到一些TS类型与类型之间需转换之处,这时你会怎么做。强大TS类型系统贴心的为开发者提供了部分常用的内置全局工具类型。

我们一起来看看吧。GO GO GO

Partial

其构造一个将 Type 的所有属性设置为可选的类型。此工具将返回一个表示给定类型的所有子集的类型。

示例:

PerInfo类型包含两个属性name和age

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

Partial 将PerInfo接口中的属性变为可选属性

ts 复制代码
type Person=Partial<PerInfo>

相当于定义了如下类型

ts 复制代码
type Person = {
    name?: string;
    age?: number;
}

Partial源码

ts 复制代码
type Partial<T> = { [P in keyof T]?: T[P] | undefined; }

Required

Partial 相反。Required把传入泛型Type的属性都变为必选项。

ts 复制代码
interface Props {
    a?: number;
    b?: string;
}

const obj: Props = { a: 5 };

const obj2: Required<Props> = { a: 5 };
// Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.

Required源码

ts 复制代码
type Required<T> = { [P in keyof T]-?: T[P]; }

Pick

从泛型Type中获取指定属性的类型,相当于得到的新类型只包含你所指定的泛型第二个参数的属性的类型。

示例:

PerInfo类型包含两个属性name和age

ts 复制代码
interface PerInfo {
    name: string;
    age: number;
    sex: string;
}

Partial 将PerInfo接口中的属性变为可选属性

ts 复制代码
type Person=Pick<PerInfo,'name'|'age'>

相当于定义了如下类型

ts 复制代码
type Person = {
    name: string;
    age: number;
}

Pick源码

ts 复制代码
type Pick<T, K extends keyof T> = { [P in K]: T[P]; }

Record

构造一个对象类型,其属性键为 Keys,其属性值为 Type。可用于将一种类型的属性映射到另一种类型。

示例:

js 复制代码
interface CatInfo {
    age: number;
    breed: string;
}

type CatName = "miffy" | "boris" | "mordred";

type Cats = Record<CatName, CatInfo>

const cats: Record<CatName, CatInfo> = {
    miffy: { age: 10, breed: "Persian" },
    boris: { age: 5, breed: "Maine Coon" },
    mordred: { age: 16, breed: "British Shorthair" },
};

cats.boris;

Record源码

ts 复制代码
type Record<K extends string | number | symbol, T> = { [P in K]: T; }

Readonly

构造一个将 Type 的所有属性设置为 readonly 的类型,这意味着构造类型的属性不能重新分配。

示例:

Omit

通过从 Type 中选择所有属性然后删除 Keys(字符串字面或字符串字面的并集)来构造一个类型。与 Pick 相反。

示例:

ts 复制代码
// 定义User类型
interface User {
    name: string;
    age: number;
    email: string;
    isActive: boolean;
    creditCardDetails: number;
}

Omit构造不包含 creditCardDetails 属性的新类型 LiUser

ts 复制代码
type LiUser = Omit<User, "creditCardDetails">;

Omit构造不包含多个属性 的新类型 TiUser

ts 复制代码
type TiUser = Omit<User, "email" | "isActive">;

Omit源码

ts 复制代码
type Omit<T, K extends string | number | symbol> = { [P in Exclude<keyof T, K>]: T[P]; }

未完待续......

相关推荐
excel21 分钟前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia31133 分钟前
https连接传输流程
前端·面试
徐小夕33 分钟前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
threelab44 分钟前
Three.js 物理模拟着色器 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
kyriewen1 小时前
CSS Container Queries:彻底告别 @media 写到手软,附 5 个真实布局案例
前端·css·面试
小小小小宇2 小时前
OpenMemory MCP
前端
和平宇宙3 小时前
AI笔记005. hermes-DeepSeek V4 Pro, 128K上下文引发的探索
前端·人工智能·笔记
IT_陈寒3 小时前
Redis持久化这个坑,我爬了一整天才出来
前端·人工智能·后端
naildingding4 小时前
3-ts接口 Interface
前端·typescript
小小前端仔LC4 小时前
Node.js + LangChain + React:搭建个人知识库(六)- “吃什么”项目实战:从700+菜谱入库到Taro H5端JSON渲染
前端·后端