TypeScript 常用内置工具类型
TypeScript 提供多个内置工具类型,日常开发高频使用,下面逐一梳理。
Partial
将类型 T 的所有属性变为可选:
TypeScript
interface User {
name: string;
age: number;
email: string;
}
type PartialUser = Partial<User>;
// 等价于:{ name?: string; age?: number; email?: string; }
function updateUser(id: string, data: Partial<User>) {
// 只需传入要更新的字段
}
updateUser("1", { name: "Alice" });
Required
将类型 T 的所有属性变为必填:
TypeScript
interface Config {
host?: string;
port?: number;
}
type FullConfig = Required<Config>;
// 等价于:{ host: string; port: number; }
Pick<T, K>
从类型 T 中挑选部分属性 K:
TypeScript
interface Article {
id: number;
title: string;
content: string;
createdAt: Date;
}
type ArticlePreview = Pick<Article, "id" | "title">;
// 等价于:{ id: number; title: string; }
function listArticles(): ArticlePreview[] {
return [{ id: 1, title: "TS 入门" }];
}
Omit<T, K>
从类型 T 中排除部分属性 K:
TypeScript
interface User {
id: string;
name: string;
password: string;
}
type SafeUser = Omit<User, "password">;
// 等价于:{ id: string; name: string; }
function createUser(data: SafeUser) {
// 不可能传入 password
}
Readonly
将类型 T 的所有属性变为只读:
TypeScript
interface Config {
apiKey: string;
endpoint: string;
}
type ImmutableConfig = Readonly<Config>;
const config: ImmutableConfig = {
apiKey: "xxx",
endpoint: "/api"
};
// config.apiKey = "yyy"; // ❌ 无法分配到只读属性
对比表
| 工具类型 | 作用 | 示例 |
|---|---|---|
Partial<T> | 全部属性变可选 | Partial<User> → { name?: string } |
Required<T> | 全部属性变必填 | Required<Config> → { host: string } |
Pick<T, K> | 挑选指定属性 | Pick<Article, "id"> → { id: number } |
Omit<T, K> | 排除指定属性 | Omit<User, "password"> → 无 password |
Readonly<T> | 全部属性变只读 | Readonly<Config> → 无法修改 |
组合使用
TypeScript
interface Product {
id: number;
name: string;
price: number;
description: string;
}
// 更新产品:排除 id,其他可选
type UpdateProduct = Partial<Omit<Product, "id">>;
// 产品摘要:只读 + 挑选
type ProductSummary = Readonly<Pick<Product, "id" | "name">>;
要点总结
Partial<T>用于部分更新对象(如 PATCH 请求)Required<T>用于确保所有字段都存在Pick<T, K>用于提取子集(如列表展示)Omit<T, K>用于排除敏感字段(如密码)Readonly<T>用于不可变配置或常量- 工具类型可组合使用,灵活应对各种场景
📝 发现内容有误?点击此处直接编辑