【发布时间】:2021-08-01 23:36:25
【问题描述】:
Typescript:什么是映射类型?
- 它是如何工作的?
- 我应该什么时候使用它?
- 示例
【问题讨论】:
标签: typescript types typescript-typings
【问题讨论】:
标签: typescript types typescript-typings
在 Typescript 中,我们有时希望基于其他类型构建类型。映射类型允许我们以非常简洁的方式基于现有类型生成新类型,这使我们遵守不要重复自己原则
自定义属性:
type customProperties = {
[key: string]: string | boolean;
};
const conforms: customProperties = {
str: 'foo',
bool: true,
// int: 123 > Error Type 'number' is not assignable to type 'string | boolean'.
};
映射类型:
type Person = {
name: string;
age: string;
};
// Demo only >> TS has a builtin Readonly, use that
type myReadonly<Type> = {
readonly [Property in keyof Type]: Type[Property];
};
// Demo only >> TS has a builtin Partial, use that
type myPartial<Type> = {
[Property in keyof Type]?: Type[Property];
};
type ReadonlyPerson = myReadonly<Person>
type PartialPerson = myPartial<Person>
请注意,映射类型使用自定义属性的语法[]: type。自定义属性和映射类型的区别如下:
[Property in keyof Type] 语法迭代现有类型的属性。它将现有类型的所有属性映射到您可以根据需要自定义的新类型。【讨论】: