在TypeScript中,类型转换(Type Transformation)是一个强大的功能,可以通过不同的方法将一种类型转换成另一种类型。以下是一些高级类型转换的示例:
1. 映射类型(Mapped Types)
映射类型可以通过在现有类型的基础上创建一个新类型。
type Person = {
name: string;
age: number;
};
// 将所有属性设为可选
type PartialPerson = {
[P in keyof Person]?: Person[P];
};
// 将所有属性设为只读
type ReadonlyPerson = {
readonly [P in keyof Person]: Person[P];
};
2. 条件类型(Conditional Types)
条件类型允许你根据条件生成不同的类型。
type IsString<T> = T extends string ? 'yes' : 'no';
type Test1 = IsString<string>; // 'yes'
type Test2 = IsString<number>; // 'no'
3. 提取和排除类型(Extract and Exclude)
Extract和Exclude用于从联合类型中提取或排除子类型。
type Union = string | number | boolean;
// 提取字符串和数字类型
type StringOrNumber = Extract<Union, string | number>; // string | number
// 排除布尔类型
type NotBoolean = Exclude<Union, boolean>; // string | number
4. 内置的类型工具(Utility Types)
TypeScript 提供了一些内置的类型工具来简化常见的类型转换。
type Person = {
name: string;
age: number;
address?: string;
};
// 将所有属性设为可选
type PartialPerson = Partial<Person>;
// 将所有属性设为只读
type ReadonlyPerson = Readonly<Person>;
// 从类型中选取部分属性
type NameAndAge = Pick<Person, 'name' | 'age'>;
// 排除某些属性
type AddresslessPerson = Omit<Person, 'address'>;
5. 索引类型查询和访问(Index Types)
索引类型查询和访问允许你动态地获取和操作类型中的属性。
type Person = {
name: string;
age: number;
};
// 获取属性类型
type NameType = Person['name']; // string
// 动态获取属性类型
type PropertyType<T, K extends keyof T> = T[K];
type AgeType = PropertyType<Person, 'age'>; // number
6. 映射联合类型(Mapped Union Types)
通过映射联合类型,可以创建更复杂的类型转换。
type Status = 'success' | 'error' | 'loading';
type StatusMessages = {
[K in Status]: K extends 'success' ? 'Operation was successful' :
K extends 'error' ? 'There was an error' :
'Loading...';
};
// StatusMessages 的类型
// {
// success: 'Operation was successful',
// error: 'There was an error',
// loading: 'Loading...'
// }
7. 递归类型(Recursive Types)
递归类型允许你定义自引用的类型。
type Tree<T> = {
value: T;
children?: Tree<T>[];
};
const tree: Tree<string> = {

最低0.47元/天 解锁文章
5617

被折叠的 条评论
为什么被折叠?



