ts重点学习96-映射类型笔记

这篇博客深入探讨了TypeScript中的Readonly、Partial类型工具以及如何创建自定义类型操作。通过实例展示了如何将接口属性设置为只读或可选,并演示了如何通过类型操作符实现接口属性的添加与删除。
摘要由CSDN通过智能技术生成
export default {}

// 旧的接口
interface IPerson {
  name: string;
  age: number;
}


// 只读
type ReadonlyTest<T> = {
  // 遍历指定类型所有的key,并添加到当前类型上
  // obj = {a: 1}  obj[a]
  readonly [P in keyof T]: T[P]
}
// type res = ReadonlyTest<IPerson>

// 可选
type PartialTest<T> = {
  [P in keyof T]?: T[P]
}

// type res = PartialTest<IPerson>


// 通过 + - 指定添加或者删除
interface IPerson2 {
  readonly name?: string;
  readonly age?: number;
}

type Test<T> = {
  -readonly [P in keyof T]-?: T[P]
}

type res = Test<IPerson2>


// Readonly / Partial
interface IPerson3 {
  name: string;
  age: number;
}
type res1 = Readonly<IPerson3>
type res2 = Partial<IPerson3>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值