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

类型并没有被直接计算出来,可以使用 xxx extends any ? xx : never OR xxx extends never ? never : xxx #7

Open
xiaochengzi6 opened this issue Feb 23, 2023 · 0 comments

Comments

@xiaochengzi6
Copy link
Owner

就比如这种

type DeepReadOnly<Obj extends Record<string, any>> = {
  readonly [Key in keyof Obj]: 
    Obj[Key] extends object
      ? Obj[Key] extends Function 
        ? Obj[Key]
        : DeepReadOnly<Obj[Key]>
      : Obj[Key]

}

type deepReadOnly = DeepReadOnly<{
  a: string
  b: number
  c: {
    d: number
    e: {
      name: string
    }
  }
}>

image
因为 ts 的类型只有被用到的时候才会做计算。

所以可以在前面加上一段 Obj extends never ? never 或者 Obj extends any 等,从而触发计算:

type DeepReadOnly<Obj extends Record<string, any>> = 
  Obj extends any ?
  {
    readonly [Key in keyof Obj]:
    Obj[Key] extends object
      ? Obj[Key] extends Function
        ? Obj[Key]
        : DeepReadOnly<Obj[Key]>
      : Obj[Key]
  }
  : never

image

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

1 participant