TypeScript类型体操 2.easy-redonly

首先看一下readme:

不要使用内置的Readonly<T>,自己实现一个。

泛型 Readonly<T> 会接收一个 泛型参数,并返回一个完全一样的类型,只是所有属性都会是只读 (readonly) 的。

也就是不可以再对该对象的属性赋值。

例如:

interface Todo {
  title: string
  description: string
}

const todo: MyReadonly<Todo> = {
  title: "Hey",
  description: "foobar"
}

todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property

第二步看下单元测试要求和原题目给的信息:

单元测试:

import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<MyReadonly<Todo1>, Readonly<Todo1>>>,
]

interface Todo1 {
  title: string
  description: string
  completed: boolean
  meta: {
    author: string
  }
}

原题目信息:

type MyReadonly<T> = any

第三步开始进行我们JS对比和TS操作:

type MyReadonly<T> = {
  //[P in T] T为一个接口无法直接遍历
  //[P in keyof T] keyof将T接口中所有数据key遍历返回
  //   interface Todo{
  //       a:string
  //       b:string
  //   }
  //   type r = keyof Todo //["a","b"]
  // const rv :r = "" //写""就会显示 a, b 证明keyof之后,是ab两个 。可以用这种方式测试
  readonly [P in keyof T] : T[P];//加上readonly方法:直接加
};

// interface User = {
//     readonly name:string
// }

// const xiaohong :User = {
//     name:"小红"
// }
// //想让用户不能改变name ,那就在类型旁边加上readonly
// xiaohong.name = "123";//readonly加上了就会报错了

//对比学习法 JS逻辑

function readonly(obj) {
  const result = {};
  for (const key in obj) {
    result["readonly" + key] = obj[key];
  }

  return result;
}

//1.返回一个对象
//2.遍历Obj (js里是对象  TS里面应该是接口) in -> mapped keyof ->looKup
//3.加上readonly关键字  新的知识点
//4.通过Key来获取Obj(接口)里面的值 indexed

最后可以看到通过了我们的单测case:

在这里插入图片描述
以上案例均上传到github TDL仓库中

TS体操-github地址:https://github.com/type-challenges/type-challenges
本人github仓库地址:https://github.com/zclsx/TDL-TS
关于配套视频教程可以参考阿崔cxr:bilibili 阿崔cxr

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值