#8•Medium

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

ChallengeSolution
// 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 Todo

Pro Challenge

Get access to all 200+ challenges, including every medium, hard, and extreme one.

One-time payment, lifetime access. 30-day money-back guarantee.

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

Related Challenges

Learn the Concepts

Become a TypeScript Pro

Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.

Or start solving right away: explore all TypeScript challenges