Disclosure

Most of the problems under my TypeHero Challenges folder were either obtained from typehero.dev or from type-challenges repo. Purpose of these articles are just to document my approaches for my easy reference. Please visit the respective links for more info.

Link to original

Problem Description

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:

interface Todo {
  title: string
  description: string
  completed: boolean
}
 
const todo: MyReadonly2<Todo, 'title' | 'description'> = {
  title: "Hey",
  description: "foobar",
  completed: false,
}
 
todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property
todo.completed = true // OK

Solutions

Approach 1: Using built-in utilities

type MyReadonly2<T, K extends keyof T = keyof T> = Readonly<Pick<T, K>> & Omit<T, K>

Notes

Check implementation notes for Readonly, The Pick Builtin and Omit.