跳到主要内容

Deep Readonly

介绍

实现通用DeepReadonly<T>,让对象的每个参数-且子对象迭代只读

你可以假设在这个挑战中我们只处理对象. 数组, 函数, 类等等不需要考虑. 然而, 你仍然可以通过处理尽可能多的不同案例来挑战自己.

For example

ts
type X = {
x: {
a: 1
b: 'hi'
}
y: 'hey'
}
type Expected = {
readonly x: {
readonly a: 1
readonly b: 'hi'
}
readonly y: 'hey'
}
const todo: DeepReadonly<X> // should be same as `Expected`
ts
type X = {
x: {
a: 1
b: 'hi'
}
y: 'hey'
}
type Expected = {
readonly x: {
readonly a: 1
readonly b: 'hi'
}
readonly y: 'hey'
}
const todo: DeepReadonly<X> // should be same as `Expected`
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type DeepReadonly<T> = any
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<DeepReadonly<X>, Expected>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
type X = {
a: () => 22
b: string
c: {
d: boolean
e: {
g: {
h: {
i: true
j: 'string'
}
k: 'hello'
}
}
}
}
 
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'
}
}
}
}
ts
/* _____________ Your Code Here _____________ */
 
type DeepReadonly<T> = any
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<DeepReadonly<X>, Expected>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
type X = {
a: () => 22
b: string
c: {
d: boolean
e: {
g: {
h: {
i: true
j: 'string'
}
k: 'hello'
}
}
}
}
 
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'
}
}
}
}
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
type DeepReadonly<T> = {
readonly [P in keyof T]: keyof T[P] extends never ? T[P] : DeepReadonly<T[P]>
}
ts
type DeepReadonly<T> = {
readonly [P in keyof T]: keyof T[P] extends never ? T[P] : DeepReadonly<T[P]>
}
view more solutions