readonly

作者: sweetBoy_9126 | 来源:发表于2022-07-17 18:08 被阅读0次

测试case

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
  }
}
  • template.ts
type MyReadonly<T> = any

相关知识点

  1. keyof T
    获取 T 接口的所有的key(联合类型)
interface A {
  a: 1,
  b: 2
}
keyof A // 'a' | 'b' 
  1. in keyof T
    遍历生成每一个 T 的key
interface A {
  a: 1,
  b: 2
}
type r = {
  [P in keyof T]: T[P]
}
// 等价于
type r = {
  a: number
  b: number
}

js 实现

const myReadonly = (obj) => {
  const result = {}
  for (let key in obj) {
    result[`readonly${key}`] = obj[key]
  }
  return result
}

步骤:

    1. 返回一个对象
    1. 遍历obj (js 指的是对象,ts 指的是接口)
    1. 加上 readonly 前缀
    1. 通过 key 来获取 obj 的值

ts 实现

//1. = {}
//2. [P in keyof T]
//3. readonly [P in keyof T]
//4. T[P]
type MyReadonly<T> = {
  readonly [P in keyof T]: T[P]
}

相关文章

网友评论

      本文标题:readonly

      本文链接:https://www.haomeiwen.com/subject/ojjlirtx.html