TypeScript系列教程九《类型转换》-- 映射类型

48 阅读2分钟

类型转换是TS最好玩也是语言的灵魂,想玩好需要熟练各种手段和工具,下面一一介绍类型转换的一些常用手段。

Mapped Types



有时候对象属性类型重复或者一个类型基于另一个了类型的时候

映射类型基于索引签名的语法构建,用于声明尚未提前声明的属性类型:

type OnlyBoolsAndHorses = {

[key: string]: boolean | Horse;

};

const conforms: OnlyBoolsAndHorses = {

del: true,

rodney: false,

};

泛型映射类型使用keyof 得到联合类型,通过key 迭代创建新类型

type OptionsFlags = {

};

在这个例子里,OptionsFlags将会把Type所有的属性当做key,所有的值类型变成boolean

type FeatureFlags = {

darkMode: () => void;

newUserProfile: () => void;

};

type FeatureOptions = OptionsFlags;

//type FeatureOptions = {

//darkMode: boolean;

// newUserProfile: boolean;

//}

映射修饰

有两个附加的修饰符可以在映射期间应用:readonly和?分别影响可变性和可选性。

可以通过在前面加上-或+,删除或添加这些修饰符。如果不添加前缀,则假定为+。

// Removes 'readonly' attributes from a type's properties

type CreateMutable = {

-readonly Property in keyof Type: Type[Property];

};

type LockedAccount = {

readonly id: string;

readonly name: string;

};

type UnlockedAccount = CreateMutable;

//type UnlockedAccount = {

//id: string;

//name: string;

//}

// Removes 'optional' attributes from a type's properties

type Concrete = {

Property in keyof Type-?: Type[Property];

};

type MaybeUser = {

id: string;

name?: string;

age?: number;

};

type User = Concrete;

//type User = {

//id: string;

//name: string;

//age: number;

//}

key 通过as 重新映射

在TypeScript 4.1及更高版本中,您可以使用映射类型中的as子句重新映射映射映射类型中的键:

type MappedTypeWithNewProperties = {

}

您可以利用模板文字类型等功能从以前的属性名称创建新的属性名称:

type Getters = {

[Property in keyof Type as get${Capitalize<string & Property>}]: () => Type[Property]

};

interface Person {

name: string;

age: number;

location: string;

}

type LazyPerson = Getters;

//type LazyPerson = {

//getName: () => string;

//getAge: () => number;

//getLocation: () => string;

//}

您可以通过条件类型生成never来筛选出键:

// Remove the 'kind' property

type RemoveKindField = {