TypeScript-键盘映射

本文介绍了TypeScript中的映射类型,如如何使用+/-操作符创建只读或可选属性,以及如何利用Readonly和Partial内置工具类型。还讲解了Pick映射类型用于选取原有类型的部分属性,以及Record映射类型用于根据一个类型的所有属性创建新的映射类型。通过实例展示了这些类型的用法,帮助理解TypeScript高级类型系统的灵活性。
摘要由CSDN通过智能技术生成

1.什么是映射类型?
根据旧的类型创建出新的类型, 我们称之为映射类型
我们可以通过+/-来指定添加还是删除 只读和可选修饰符

interface TestInterface1{
    name:string,
    age:number
}
interface TestInterface2{
    readonly name?:string,
    readonly age?:number
}
type ReadonlyTestInterface<T> = {
    // [P in keyof T]作用: 遍历出指定类型所有的key, 添加到当前对象上
    // readonly [P in keyof T]: T[P]
    // readonly [P in keyof T]?: T[P]
    -readonly [P in keyof T]-?: T[P]
}
//将TestInterface2取消只读和可选
//type MyType ={
//    name:string,
//    age:number
//}
type MyType = ReadonlyTestInterface<TestInterface2>

2.由于生成只读属性和可选属性比较常用, 所以TS内部已经给我们提供了现成的实现

/*只读
type MyType2 = {
    readonly name:string,
    readonly age:number
}
*/
type MyType2 = Readonly<TestInterface1>


/*可选
type MyType3 = {
    name?:string,
   age?:number
}
*/
type MyType3 = Partial<TestInterface1>



/*只读可选
MyType4 ={
    readonly name?:string,
    readonly age?:number
}
*/
type MyType4 = Partial<Readonly<TestInterface1>>

3.Pick映射类型
将原有类型中的部分内容映射到新类型中

interface TestInterface {
    name:string,
    age:number
}
/*type MyType =  {
    name:string,
*/
type MyType = Pick<TestInterface, 'name'>

4.Record映射类型
他会将一个类型的所有属性值都映射到另一个类型上并创造一个新的类型

type Animal = 'person' | 'dog' | 'cat';
interface TestInterface {
    name:string;
    age:number;
}
type MyType = Record<Animal, TestInterface>
/*type MyType ={
    person:TestInterface,
    dog:TestInterface,
    cat:TestInterface
}
*/
let res:MyType = {
    person:{
        name:'zs',
        age:18
    },
    dog:{
        name:'wc',
        age:3
    },
    cat:{
        name:'mm',
        age:2
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值