核心工具类型
1. Partial<T>
: 让所有属性变为可选
- 作用: 构造一个类型,使其属性都变为可选。
示例:
php
```typescript
interface User {
id: number;
name: string;
email: string;
}
// 假设我们要更新用户,可能只修改姓名或邮箱
type PartialUser = Partial<User>;
/* 等同于:
type PartialUser = {
id?: number;
name?: string;
email?: string;
}
*/
function updateUser(id: number, changes: PartialUser) {
// ... 调用 API 更新数据库
console.log(`Updating user ${id} with:`, changes);
}
updateUser(1, { name: 'Alice' }); // ✅ 只传入部分属性
updateUser(2, { email: 'bob@example.com' }); // ✅
```
2. Required<T>
: 让所有属性变为必选
- 作用: 构造一个类型,使其所有属性都变为必选。
示例:
ini
```typescript
interface Product {
id: string;
name: string;
description?: string; // 描述是可选的
price: number;
}
// 有时,我们需要确保所有字段都存在,例如在提交表单前
type CompleteProduct = Required<Product>;
/* 等同于:
type CompleteProduct = {
id: string;
name: string;
description: string; // 现在是必选的
price: number;
}
*/
const newProduct: CompleteProduct = {
id: 'p001',
name: '电视',
description: '最新的电视', // 现在必须提供
price: 999.99,
//description: '最新的电视', // 现在必须提供
};
const incompleteProduct: CompleteProduct = { id: "p002", name: "Monitor", price: 299.99 }; // error: 缺少 'description' 属性
```
3. Readonly<T>
: 让所有属性变为只读
- 作用: 构造一个类型,使其所有属性都变为只读 (Immutable)。
示例:
vbnet
```typescript
interface AppConfig {
version: string;
apiUrl: string;
debugMode: boolean;
}
const config: Readonly<AppConfig> = {
version: '1.0.0',
apiUrl: 'https://api.example.com',
debugMode: false,
};
// config.version = "1.0.1"; // error:无法分配到 "version" ,因为它是一个只读属性。
```
4. Pick<T, K>
: 挑选指定属性
- 作用: 从类型
T
中挑选出由K
指定的(字面量联合类型)属性,来构造一个新的类型。
示例:
ini
```typescript
interface UserDetails {
id: number;
username: string;
email: string;
avatarUrl: string;
createdAt: Date;
}
// 我们可能只需要用户的公共个人资料信息
type UserProfile = Pick<UserDetails, 'id' | 'username' | 'avatarUrl'>;
/* 等同于:
type UserProfile = {
id: number;
username: string;
avatarUrl: string;
}
*/
const profile: UserProfile = {
id: 1,
username: 'john_doe',
avatarUrl: 'https://example.com/avatar1.png',
};
```
5. Omit<T, K>
: 排除指定属性
- 作用: 从类型
T
中排除由K
指定的(字面量联合类型)属性,来构造一个新的类型。它是Pick
的反向操作。
示例:
ini
```typescript
interface BlogPost {
id: number;
title: string;
content: string;
authorId: number;
createdAt: Date;
updatedAt: Date;
}
// 创建新博客时,id、createdAt 和 updatedAt 通常是自动生成的,不需要提供
type CreateBlogPostDto = Omit<BlogPost, 'id' | 'createdAt' | 'updatedAt'>;
/* 等同于:
type CreateBlogPostDto = {
title: string;
content: string;
authorId: number;
}
*/
const newPost: CreateBlogPostDto = {
title: 'My First Blog Post',
content: 'Hello world!',
authorId: 101,
};
```
6. Record<K, T>
: 构造字典类型
-
作用: 构造一个对象类型,其属性键是
K
类型,属性值是T
类型。 -
示例:
typescripttype Fruit = 'apple' | 'banana' | 'orange'; // 定义一个水果价格表 type FruitPrices = Record<Fruit, number>; /* 等同于: type FruitPrices = { apple: number; banana: number; orange: number; } */ const prices: FruitPrices = { apple: 1.2, banana: 0.75, orange: 1.2, };
总结
如果你喜欢本教程,记得点赞+收藏!关注我获取更多JavaScript/TypeScript开发干货