#8Medium

Readonly 2

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:

Challenge Instructions: Readonly 2

Medium

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

Change the following code to make the test cases pass (no type check errors).

Loading...

Video Walkthrough

Detailed Explanation

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:

This 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.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount