Readonly2
#
introductionImplement 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
interface Todo {title: stringdescription: stringcompleted: boolean}const todo: MyReadonly2<Todo, 'title' | 'description'> = {title: "Hey",description: "foobar",completed: false,}todo.title = "Hello" // Error: cannot reassign a readonly propertytodo.description = "barFoo" // Error: cannot reassign a readonly propertytodo.completed = true // OK
View on GitHubts
interface Todo {title: stringdescription: stringcompleted: boolean}const todo: MyReadonly2<Todo, 'title' | 'description'> = {title: "Hey",description: "foobar",completed: false,}todo.title = "Hello" // Error: cannot reassign a readonly propertytodo.description = "barFoo" // Error: cannot reassign a readonly propertytodo.completed = true // OK
#
start pointtsTry
/* _____________ 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 solutionsSpoiler warning // Click to reveal answer
tsTry
typeMyOmit <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 >Â
tsTry
typeMyOmit <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 >Â