TypeScript 进阶必修课:解锁强大的内置工具类型(一)

核心工具类型

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 类型。

  • 示例:

    typescript 复制代码
    type 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开发干货

相关推荐
weixin_382395239 小时前
为小工厂量身打造:本地部署的物料管理系统带缺料计算
前端·制造
__zRainy__9 小时前
解决pnpm v10+不自动构建
前端·pnpm·工程化
猫猫不是喵喵.9 小时前
Vue3 Props 属性
前端·javascript·vue.js
醉城夜风~10 小时前
CSS元素显示模式(display)
前端·css
AI大模型-小华11 小时前
Codex 三方充值快速入门指南
java·前端·数据库·chatgpt·ai编程·codex·chatgpt pro
做前端的娜娜子13 小时前
同一链接实现 PC Web 与移动 H5 自适应
前端·掘金·金石计划
小帅不太帅14 小时前
架构没变、规模没变,DeepSeek V4 Flash 正式版凭什么暴涨 47 分?
前端·aigc·deepseek
jarvisuni14 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
卷福同学15 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端