Deep Readonly
介绍
实现通用DeepReadonly<T>
,让对象的每个参数-且子对象迭代只读
你可以假设在这个挑战中我们只处理对象. 数组, 函数, 类等等不需要考虑. 然而, 你仍然可以通过处理尽可能多的不同案例来挑战自己.
For example
ts
type X = {x: {a: 1b: 'hi'}y: 'hey'}type Expected = {readonly x: {readonly a: 1readonly b: 'hi'}readonly y: 'hey'}const todo: DeepReadonly<X> // should be same as `Expected`
View on GitHubts
type X = {x: {a: 1b: 'hi'}y: 'hey'}type Expected = {readonly x: {readonly a: 1readonly b: 'hi'}readonly y: 'hey'}const todo: DeepReadonly<X> // should be same as `Expected`
起点
ts
/* _____________ Your Code Here _____________ */typeDeepReadonly <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <DeepReadonly <X >,Expected >>,]typeX = {a : () => 22b : stringc : {d : booleane : {g : {h : {i : truej : 'string'}k : 'hello'}}}}typeExpected = {readonlya : () => 22readonlyb : stringreadonlyc : {readonlyd : booleanreadonlye : {readonlyg : {readonlyh : {readonlyi : truereadonlyj : 'string'}readonlyk : 'hello'}}}}
take the challengets
/* _____________ Your Code Here _____________ */typeDeepReadonly <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <DeepReadonly <X >,Expected >>,]typeX = {a : () => 22b : stringc : {d : booleane : {g : {h : {i : truej : 'string'}k : 'hello'}}}}typeExpected = {readonlya : () => 22readonlyb : stringreadonlyc : {readonlyd : booleanreadonlye : {readonlyg : {readonlyh : {readonlyi : truereadonlyj : 'string'}readonlyk : 'hello'}}}}
解决方案
Spoiler warning // Click to reveal answer
ts
typeDeepReadonly <T > = {readonly [P in keyofT ]: keyofT [P ] extends never ?T [P ] :DeepReadonly <T [P ]>}
ts
typeDeepReadonly <T > = {readonly [P in keyofT ]: keyofT [P ] extends never ?T [P ] :DeepReadonly <T [P ]>}