Implement a generic `MyReadonly2<T, K>` which takes two type argument `T` and `K`. Learn how to use `readonly` modifiers in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a generic MyReadonly2<T, K> which takes
two type arguments:
T: a type to modifyK: the keys that should be set to readonlyImplement 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 // OKChange the following code to make the test cases pass (no type check errors).
type MyReadonly2<T, K extends keyof T = keyof T> = {
readonly [Key in K]: T[Key]
} & { [Key in keyof T as Key extends K ? never : Key]: T[Key] }How it works:
K to be a subset of the keys of T (keyof T)K to keyof T, handling the case where K is not provided and is supposed to be all keys of TK and the keys in T that are not in Kreadonly modifier is applied to the keys in K& operator is used to combine the two typesThis challenge helps you understand how to use readonly modifiers and how to apply this concept in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount