Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TS体操--DeepReadonly #476

Open
lhp96 opened this issue Feb 19, 2023 · 1 comment
Open

TS体操--DeepReadonly #476

lhp96 opened this issue Feb 19, 2023 · 1 comment

Comments

@lhp96
Copy link
Contributor

lhp96 commented Feb 19, 2023

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],看是否有对象的键
@gswysy
Copy link

gswysy commented Mar 13, 2024

type DeepReadonly<T> = {
    readonly [p in keyof T] : T[p] extends object ? DeepReadonly<T[p]> : T[p]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants