#7Easy

Readonly

Learn to implement TypeScript's built-in Readonly utility type from scratch. Master readonly properties and mapped types with this easy-level TypeScript challenge on TypeScriptPro.

Learn how to build TypeScript's essential utility type: Readonly! 🔒

In this easy-level challenge, you'll implement the built-in Readonly<T> generic without using the actual Readonly utility. This type constructs a new type with all properties of T set to readonly, meaning the properties of the constructed type cannot be reassigned. It's a fundamental tool for creating immutable data structures in TypeScript.

You'll be creating a type that makes all properties of an object type read-only. This is extremely useful for preventing accidental mutations and ensuring data integrity in your TypeScript applications.

For this challenge, you will need to change the following code to make the tests pass (no type check errors).

Challenge Instructions: Readonly

Easy

Implement the built-in Readonly<T> generic without using it.

Constructs a type with all properties of T set to readonly, meaning the properties of the constructed type cannot be reassigned.

For example:

interface Todo {
title: string
description: string
}
 
const todo: MyReadonly<Todo> = {
title: "Hey",
description: "foobar"
}
 
todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property
Loading...

Video Walkthrough

Detailed Explanation

To implement the Readonly utility type, you need to understand mapped types and the readonly modifier.

The solution uses TypeScript's mapped types to iterate over all properties and add the readonly modifier:

type MyReadonly<T> = {
  readonly [Key in keyof T]: T[Key]
}

Let's break this down:

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

This challenge is originally from here.