八、高级类型
1. 映射类型(Mapped Types)
映射类型(Mapped Types)是 TypeScript 中一种强大的类型操作工具,它允许我们在编译时转换已知类型的属性,并创建一个新的类型。通过映射类型,我们可以对已有类型的属性进行转换、修改或添加新的属性。这在许多情况下都非常有用,例如将属性变为只读或可选,从现有属性中选择一部分属性等。
映射类型的语法形式为:
type NewType = { [Property in keyof ExistingType]: TransformType;};
其中,NewType 是我们要创建的新类型,Property 是 ExistingType 的键,TransformType 是对应属性的转换类型。
下面是一些常见的映射类型的示例:
1) Readonly
Readonly 是 TypeScript 内置的一个映射类型,它将给定类型的所有属性变为只读。
type Readonly = { readonly [P in keyof T]: T[P];};
示例使用:
interface Person { name: string; age: number;} type ReadonlyPerson = Readonly; const person: ReadonlyPerson = { name: "John", age: 30,}; person.name = "Alice"; // Error: Cannot assign to 'name' because it is a read-only property.
2) Partial
Partial 是另一个内置的映射类型,它将给定类型的所有属性变为可选。
type Partial = { [P in keyof T]?: T[P];};
示例使用:
interface Person { name: string; age: number;} type PartialPerson = Partial; const person: PartialPerson = { name: "John",}; person.age = 30; // Valid: age is optional
3) Pick
Pick 是一个映射类型,它从给定类型中选择一部分属性来创建新类型。
type Pick = { [P in K]: T[P];};
示例使用:
interface Person { name: string; age: number; occupation: string;} type PersonInfo = Pick; const info: PersonInfo = { name: "John", age: 30,};
带你读《现代TypeScript高级教程》八、高级类型(2)https://developer.aliyun.com/article/1348532?groupCode=tech_library