Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step
https://juejin.cn/column/7244788137410560055
2.02k stars 235 forks source link

TS体操--DeepReadonly #476

Open lhp96 opened 1 year ago

lhp96 commented 1 year ago
type X = {
  a: () => 22
  b: string
  c: {
    d: boolean
    e: {
      g: {
        h: {
          i: true
          j: 'string'
        }
        k: 'hello'
      }
      l: [
        'hi',
        {
          m: ['hey']
        },
      ]
    }
  }
}

type Expected = {
  readonly a: () => 22
  readonly b: string
  readonly c: {
    readonly d: boolean
    readonly e: {
      readonly g: {
        readonly h: {
          readonly i: true
          readonly j: 'string'
        }
        readonly k: 'hello'
      }
      readonly l: readonly [
        'hi',
        {
          readonly m: readonly ['hey']
        },
      ]
    }
  }
}

// Your Answer
type DeepReadonly<T> = {
  +readonly [P in keyof T]: keyof T[P] extends never ? T[P] : DeepReadonly<T[P]>
}

// keyof T[P],看是否有对象的键
Aurora-GSW commented 8 months ago
type DeepReadonly<T> = {
    readonly [p in keyof T] : T[p] extends object ? DeepReadonly<T[p]> : T[p]
}
jianxingyao commented 5 months ago
type MyReadonly<T extends Record<string, any>> = {
    readonly [K in keyof T]:T[K] extends Record<string, any> ? MyReadonly<T[K]> : T[K];
}

一个递归 主要在于判断是不是对象形式的类型 如果是就递归