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).
// Video Solution: https://youtube.com/watch?v=kSnFXYvuJV8
/* _____________ Your Code Here _____________ */
type MyReadonly2<T, K> = any
/* _____________ Test Cases _____________ */
import type { Alike, Expect } from '../helpers'
type cases = [
Expect<Alike<MyReadonly2<Todo1>, Readonly<Todo1>>>,
Expect<Alike<MyReadonly2<Todo1, 'title' | 'description'>, Expected>>,
Expect<Alike<MyReadonly2<Todo2, 'title' | 'description'>, Expected>>,
Expect<Alike<MyReadonly2<Todo2, 'description'>, Expected>>,
]
// @ts-expect-error
type error = MyReadonly2<Todo1, 'title' | 'invalid'>
interface TodoGet access to all 200+ challenges, including every medium, hard, and extreme one.
One-time payment, lifetime access. 30-day money-back guarantee.
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.
Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.
Or start solving right away: explore all TypeScript challenges