TypeScript 高级类型系统
TypeScript 的类型系统非常强大,本文将深入探讨一些高级类型特性。
条件类型
根据条件选择不同的类型:
type IsString<T> = T extends string ? true : false;
type Test1 = IsString<string>; // true
type Test2 = IsString<number>; // false
// 实用示例:提取函数返回类型
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function getName(): string {
return "John";
}
type NameType = ReturnType<typeof getName>; // string
映射类型
基于现有类型创建新类型:
type Partial<T> = {
[P in keyof T]?: T[P];
};
type Required<T> = {
[P in keyof T]-?: T[P];
};
interface User {
id: number;
name: string;
email?: string;
}
type PartialUser = Partial<User>; // 所有属性都变为可选
type RequiredUser = Required<User>; // 所有属性都变为必需
模板字面量类型
构建字符串类型:
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"
type HoverEvent = EventName<"hover">; // "onHover"
// 实用示例:API 路径类型
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type ApiPath = "/users" | "/posts" | "/comments";
type ApiEndpoint = `${HttpMethod} ${ApiPath}`;
// "GET /users" | "POST /users" | ... 等所有组合
工具类型组合
创建复杂的类型转换:
// 深度只读
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
// 选择性必需
type RequireFields<T, K extends keyof T> = T & Required<Pick<T, K>>;
interface UserProfile {
id?: number;
name?: string;
email?: string;
avatar?: string;
}
type UserWithRequiredName = RequireFields<UserProfile, "name">;
// { id?: number; name: string; email?: string; avatar?: string; }
总结
TypeScript 的高级类型系统为我们提供了强大的类型安全保障和代码提示功能。掌握这些特性能让你写出更健壮的代码。