#9Medium

Deep Readonly

Implement a generic `DeepReadonly<T>` which makes every parameter of an object - and its sub-objects recursively - readonly. Learn readonly modifiers in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement a generic DeepReadonly<T>, which makes every parameter of an object - and its sub-objects recursively - readonly.

Challenge Instructions: Deep Readonly

Medium

Implement a generic DeepReadonly<T> which make every parameter of an object - and its sub-objects recursively - readonly.

You can assume that we are only dealing with Objects in this challenge. Arrays, Functions, Classes and so on do not need to be taken into consideration. However, you can still challenge yourself by covering as many different cases as possible.

For example:

type X = {
x: {
a: 1
b: 'hi'
}
y: 'hey'
}
 
type Expected = {
readonly x: {
readonly a: 1
readonly b: 'hi'
}
readonly y: 'hey'
}
 
type Todo = DeepReadonly<X> // should be same as `Expected`

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

Loading...

Video Walkthrough

Detailed Explanation

To make an object deeply readonly, we need recursion:

type DeepReadonly<T> = T extends Function
  ? T
  : {
      readonly [K in keyof T]: DeepReadonly<T[K]>
    }

How it works:

This challenge helps you understand 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