Readonly2
introduction#
Implement a generic MyReadonly2<T, K> which takes two type argument T and K.
K specify the set of properties of T that should set to Readonly. When K is not provided, it should make all properties readonly just like the normal Readonly<T>.
For example
ts
View on GitHubts
start point#
tsTry/* _____________ Your Code Here _____________ */ÂtypeMyReadonly2 <T ,K > = anyÂ/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Alike <MyReadonly2 <Todo1 , 'title' | 'description'>,Expected >>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Alike <MyReadonly2 <Todo2 , 'title' | 'description'>,Expected >>,]ÂinterfaceTodo1 {title : stringdescription ?: stringcompleted : boolean}ÂinterfaceTodo2 {readonlytitle : stringdescription ?: stringcompleted : boolean}ÂinterfaceExpected {readonlytitle : stringreadonlydescription ?: stringcompleted : boolean}Â
take the challengetsTry/* _____________ Your Code Here _____________ */ÂtypeMyReadonly2 <T ,K > = anyÂ/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Alike <MyReadonly2 <Todo1 , 'title' | 'description'>,Expected >>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Alike <MyReadonly2 <Todo2 , 'title' | 'description'>,Expected >>,]ÂinterfaceTodo1 {title : stringdescription ?: stringcompleted : boolean}ÂinterfaceTodo2 {readonlytitle : stringdescription ?: stringcompleted : boolean}ÂinterfaceExpected {readonlytitle : stringreadonlydescription ?: stringcompleted : boolean}Â
my solutions#
Spoiler warning // Click to reveal answer
tsTrytypeMyOmit <T ,K extends string | number | symbol> = {[Key inExclude <keyofT ,K >]:T [Key ]}ÂtypeMyReadonly2 <T ,K extends keyofT = keyofT > = {readonly [Key inK ]:T [Key ]} &MyOmit <T ,K >Â
tsTrytypeMyOmit <T ,K extends string | number | symbol> = {[Key inExclude <keyofT ,K >]:T [Key ]}ÂtypeMyReadonly2 <T ,K extends keyofT = keyofT > = {readonly [Key inK ]:T [Key ]} &MyOmit <T ,K >Â