模块课程(2/2)
实用程序类型
TypeScript 提供了几种全局实用程序类型来促进常见类型转换。这些类型是通用的,允许您以声明方式从现有类型构建新类型。
四种最常用的实用程序类型是:
1.Partial<T>
使 T 类型的所有属性可选。这对于更新/修补函数非常有用,其中调用者可能只提供字段的子集:
interface User {
id: number;
name: string;
email: string;
}
// All properties of User become optional: { id?: number; name?: string; email?: string; }
type UserUpdate = Partial<User>;2.Readonly<T>
使 T 类型的所有属性只读。任何重新分配属性的尝试都会触发编译时编译器错误:
interface Point {
x: number;
y: number;
}
const p: Readonly<Point> = { x: 10, y: 20 };
// p.x = 5; // Error: cannot assign to 'x' because it is a read-only property3.Pick<T, Keys>
通过从类型 T 中仅选择一组特定的键(由字符串并集表示)来创建类型:
interface Article {
id: number;
title: string;
content: string;
views: number;
}
// Selects only 'title' and 'views': { title: string; views: number; }
type ArticlePreview = Pick<Article, 'title' | 'views'>;4.Omit<T, Keys>
通过从类型 T 中删除一组特定的键来创建类型。它是 Pick 的对偶:
interface Product {
id: number;
name: string;
price: number;
secretVendorCode: string;
}
// Removes 'secretVendorCode': { id: number; name: string; price: number; }
type PublicProduct = Omit<Product, 'secretVendorCode'>;5.Record<Keys, Type>
创建一个对象类型,其属性键为 Keys,其属性值为 Type。它对于将键映射到值、表示字典或哈希表(键值映射)非常有用:
type Page = 'home' | 'about' | 'contact';
interface PageInfo {
title: string;
}
// Creates a dictionary with keys 'home' | 'about' | 'contact' and values PageInfo
const nav: Record<Page, PageInfo> = {
home: { title: 'Home Page' },
about: { title: 'About Us' },
contact: { title: 'Contact Us' },
};自己尝试一下
练习 1:使用部分更新配置文件
完成 updateProfile 函数,该函数接受原始配置文件(Profile)和更新对象(updates),其中 Profile 的所有字段都是可选的。它必须返回一个新的 Profile 对象,该对象将原始属性与更新相结合。
显示提示
使用 Partial<Profile> 实用程序类型作为更新参数,并使用展开运算符来合并对象:{ ...original, ...updates }。
3 次尝试后可用的解决方案
练习 2:使用 Omit 删除敏感字段
给定 UserAccount 类型,定义一个名为 SafeUser 的类型别名,该别名忽略敏感的 passwordHash 属性。
显示提示
使用类型 SafeUser = Omit<UserAccount, 'passwordHash'>;省略指定字段。
3 次尝试后可用的解决方案
练习 3:带有 Pick 和 Readonly 的公共配置
给定 AppConfig 类型,定义一个名为 PublicConfig 的类型别名,它是一个只读 (Readonly) 版本,仅包含使用 Pick 选择的 apiEndpoint 和端口属性。
显示提示
使用类型 PublicConfig = Readonly<Pick<AppConfig, 'apiEndpoint' | '端口'>>;
3 次尝试后可用的解决方案
练习 4:具有记录和只读的用户注册表
给定一个包含字段 id: number 和 name: string 的用户界面,创建一个 ReadOnlyUser 类型,使 User 中的所有字段变为只读。然后,创建一个 UserRegistry 类型,它表示一个字典,其中键是字符串(例如字符串 id),值是 ReadOnlyUser。
显示提示
使用 Readonly<User> 定义 ReadOnlyUser,并使用 Record<string, ReadOnlyUser> 定义注册表。
3 次尝试后可用的解决方案