当你不想重复自己的时候,有时一个类型需要基于另一个类型。映射类型建立在索引签名的语法基础上,用于声明尚未提前声明的属性类型:
type OnlyBoolsAndHorses = {
[key: string]: boolean | Horse;
};
const conforms: OnlyBoolsAndHorses = {
del: true,
rodney: false,
};
映射类型是一种泛型类型,它使用PropertyKey
的联合(通常通过keyof创建)来遍历键以创建类型:
type OptionsFlags<Type> = {
[Property in keyof Type]: boolean;
};
在这个例子中,OptionsFlags
将从类型Type
中获取所有属性,并将它们的值更改为布尔值。
type Features = {
darkMode: () => void;
newUserProfile: () => void;
};
type FeatureOptions = OptionsFlags<Features>;
// 结果
type FeatureOptions = {
darkMode: boolean;
newUserProfile: boolean;
}
映射修改器
有两个附加的修饰符可以在映射过程中应用:readonly和?
它们分别影响可变性和可选性。
您可以通过添加前缀-或+来
删除或添加这些修饰符。如果不添加前缀,则假定为+
。
// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property];
};
type LockedAccount = {
readonly id: string;
readonly name: string;
};
type UnlockedAccount = CreateMutable<LockedAccount>;
// 结果
type UnlockedAccount = {
id: string;
name: string;
}
// Removes 'optional' attributes from a type's properties
type Concrete<Type> = {
[Property in keyof Type]-?: Type[Property];
};
type MaybeUser = {
id: string;
name?: string;
age?: number;
};
type User = Concrete<MaybeUser>;
// 结果
type User = {
id: string;
name: string;
age: number;
}
通过 as重映射
在TypeScript 4.1及以后版本中,你可以在映射类型中使用as
子句重新映射映射类型中的键:
type MappedTypeWithNewProperties<Type> = {
[Properties in keyof Type as NewKeyType]: Type[Properties]
}
您可以利用模板文字类型等功能从以前的属性名创建新的属性名:
type Getters<Type> = {
[Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]
};
interface Person {
name: string;
age: number;
location: string;
}
type LazyPerson = Getters<Person>;
// 结果
type LazyPerson = {
getName: () => string;
getAge: () => number;
getLocation: () => string;
}
你可以使用never
通过条件类型来过滤键:
// Remove the 'kind' property
type RemoveKindField<Type> = {
[Property in keyof Type as Exclude<Property, "kind">]: Type[Property]
};
interface Circle {
kind: "circle";
radius: number;
}
type KindlessCircle = RemoveKindField<Circle>;
// 结果
type KindlessCircle = {
radius: number;
}
您可以映射任意的联合,而不仅仅是 string | number | symbol
,但任何类型的联合:
type EventConfig<Events extends { kind: string }> = {
[E in Events as E["kind"]]: (event: E) => void;
}
type SquareEvent = { kind: "square", x: number, y: number };
type CircleEvent = { kind: "circle", radius: number };
type Config = EventConfig<SquareEvent | CircleEvent>
// 结果
type Config = {
square: (event: SquareEvent) => void;
circle: (event: CircleEvent) => void;
}
进一步探索
映射类型与此类型操作部分中的其他功能配合良好,例如,这里是一个使用条件类型的映射类型,该类型返回true
或false,这
取决于对象是否将属性pii
设置为 true
:
type ExtractPII<Type> = {
[Property in keyof Type]: Type[Property] extends { pii: true } ? true : false;
};
type DBFields = {
id: { format: "incrementing" };
name: { type: string; pii: true };
};
type ObjectsNeedingGDPRDeletion = ExtractPII<DBFields>;
// 结果
type ObjectsNeedingGDPRDeletion = {
id: false;
name: true;
}