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).
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
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:
[Key in keyof T]
iterates over each property key in type T
readonly
modifier is applied to each propertyT[Key]
preserves the original type of each propertyBe the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount
This challenge is originally from here.