持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第2天,点击查看活动详情
1. 引言
今天是我们TypeScript类型系统第二课,让我们来了解下在类型系统中 最常用的类型方法————类型映射方法,简单来说就是像JavaScript 的map函数方法,把一种类型装换为另一种类型 它是建立在 索引签名 的语法上。
2. 含义
作为类型检测语法中的类型装换方式,常见很多内置的类型语法中普遍存在,比如:Partial ,Required ,Readonly ,Pick ,Record ,等
它的基本类型语法是:
{[P in K]: T}
3. 常见映射类型语法
// 遍历类型,通过keyof 获取到所变量类型的所有键值,来循环遍历,在通过 in 获取对应循环键名及值通过映射方式生产新属性新值,此为映射
{ [Property in keyof Type]:T }
// 此为全量映射
// 在映射期间可以使用两个额外的映射修饰符 readonly:属性只读;?:属性可选;前缀 -(代表删除)或者+(代表新增属性,默认新增属性不用标注)
type Partial<T> = { [P in keyof K] ?: T[P] }// 全部设置为可选属性
type Required<T> = { [P in keyof K] -?: T[P] }// 移除可选属性
type Readonly = { readonly [P in keyof K] : T[P] }// 全部设置为只读属性
type AllReadonly = { readonly [P in keyof K] ?: T[P] }// 全部设置为只读可选属性
type AllRemoveReadonly = { -readonly [P in keyof K] ?: T[P] }// 移除全部设置为只读可选属性
// 部分接口映射
type Obj = {a: string,b: number,c: boolean,d: symbol}
type MyPick = Pick<Obj,'a' | 'd'> // {a: string,d: symbol}
// 映射时,预订新的接口
type RecordObj = Record<"x" | "y", Obj>; // {x: Obj,y: Obj}
4. 例子
例句一:
type Item = {a: string,b: number,c: boolean}
type T1 = {[P in 'x' | 'y']: number} // ==> {x: number,y: number}
type T2 = {[P in 'x' | 'y']: P} // ==> {x: 'x',y: 'y'}
type T3 = {[P in 'a' | 'b']: Item[P]} // ==> {a: string,b: number}
type T4 = {[P in keyof Item]: Item[P]} // ==> {a: string,b: number,c: boolean}
例句二:
type MappedTypeWidthNewKeys<T> = {
[K in keyof T as 'NewKeysType']: T[K]
}
type a = MappedTypeWidthNewKeys<Item> // ===> {NewKeysType: string | number | boolean}
例句三:
type Getters<T extends any> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
}
type b = Getters<Item> // ====> {getA:() => string,getB: () => number,getC: () => boolean}
例句四:
type RemoveKindKeys<T> = {
[K in keyof T as Exclude<K,'c'>]: T[K]
}
type c = RemoveKindKeys<Item> // ===> {a: string,b: number}
5. 总结
处理场景:当需要一个类型需要基于另外一个类型,但是你又不想拷贝一份,这个时候可以考虑使用映射类型。
6. 思考一下
如果我有个目标接口类型为
interface Person {
name: string
age:number
sex: string
}
需要映射一个类型方法为
interface GetPerson {
getName: () => string
getAge: () => number
getSex: () => string
}
该怎么做呢??需要用到什么类型语法?大家可以自己尝试下,此系列下期公布答案。