映射类型概述
根据
旧
的类型创建出新
的类型, 我们称之为映射类型
假如如下的 TestInterface1
是旧的类型:
interface TestInterface1 { name: string, age: number }
那么这个时候根据 TestInterface1 创建出来的新的类型就称之为映射类型,例如如下的 TestInterface2
:
interface TestInterface2 { readonly name: string, readonly age: number }
如上只是一个简单的示例,接下来就来看看真实的示例,就是真实的通过旧的类型创建出来的新的类型:
type ReadonlyTestInterface<T> = { readonly [P in keyof T]: T[P] }
如上我定义了一个类型别名通过该类型别名就可以实现从旧的类型转换到新的类型,如上 [P in keyof T]
的作用就是遍历出指定类型所有的 key, 添加到当前对象上,然后使用一下该类型别名:
interface TestInterface1 { name: string, age: number } type ReadonlyTestInterface<T> = { readonly [P in keyof T]: T[P] } type MyType = ReadonlyTestInterface<TestInterface1>
测试方式很简单,就是按住键盘上的 ctrl + 鼠标左键移动到 MyType
上面即可查看最新的类型,如果还想让创建出新的类型当中的属性变为可选的那么该如何实现呢如下:
interface TestInterface1 { name: string, age: number } type ReadonlyTestInterface<T> = { readonly [P in keyof T]?: T[P] } type MyType = ReadonlyTestInterface<TestInterface1>
测试方式同上,其实还可以通过 +/-
来指定 添加
还是 删除
只读
和 可选
修饰符,假如现在的接口当中有只读和可选的属性,如果我们在创建出来的新类型的时候不想要只读和可选,那么就可以利用 -
在类型别名当中进行去除代码如下:
interface TestInterface1 { readonly name?: string, readonly age?: number } type ReadonlyTestInterface<T> = { -readonly [P in keyof T]-?: T[P] } type MyType = ReadonlyTestInterface<TestInterface1>
如果想 添加
也是同理可证的如下:
interface TestInterface1 { readonly name?: string, readonly age?: number } type ReadonlyTestInterface<T> = { +readonly [P in keyof T]+?: T[P] } type MyType = ReadonlyTestInterface<TestInterface1>
由于生成
只读
属性和可选
属性比较常用, 所以 TS 内部已经给我们提供了现成的实现Readonly
:添加只读Partial
:添加可选
interface TestInterface1 { readonly name?: string, readonly age?: number } type MyType1 = Readonly<TestInterface1>; type MyType2 = Partial<TestInterface1>; type MyType3 = Partial<Readonly<TestInterface1>>;
Pick 映射类型
将原有类型中的
部分
内容映射到新类型中
interface TestInterface { name: string, age: number } type MyType = Pick<TestInterface, 'name'>;
验证方式同上 ctrl + 鼠标左键移动到 MyType
上面即可查看最新的类型。
Record 映射类型
他会将一个类型的所有属性值都映射到另一个类型上并创造一个新的类型
type Animal = 'person' | 'dog' | 'cat'; interface TestInterface { name: string; age: number; } type MyType = Record<Animal, TestInterface>; let res: MyType = { person: { name: 'zs', age: 18 }, dog: { name: 'wc', age: 3 }, cat: { name: 'mm', age: 2 } } console.log(res);
验证方式同上 ctrl + 鼠标左键移动到 MyType
上面即可查看最新的类型。
由映射类型进行推断 对于 Readonly,Partial 和 Pick 的映射类型, 我们可以对映射之后的类型进行拆包 还原映射之前的类型, 这种操作我们称之为
拆包
interface MyInterface { name: string; age: number; } type MyType<T> = { +readonly [P in keyof T]: T[P]; } type test = MyType<MyInterface>; type UnMyType<T> = { -readonly [P in keyof T]: T[P]; } type test2 = UnMyType<test>;
验证方式 ctrl + 鼠标左键移动到 test
、test2
上面即可查看最新的类型。
最后
本期结束咱们下次再见👋~
🌊 关注我不迷路,如果本篇文章对你有所帮助,或者你有什么疑问,欢迎在评论区留言,我一般看到都会回复的。大家点赞支持一下哟~ 💗