Implement the generic ```Mutable<T>``` which makes all properties in ```T``` mutable (not readonly). Learn readonly modifiers in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement the generic Mutable<T> which removes the readonly modifier from all properties in T, making them mutable.
Implement the generic Mutable<T> which makes all properties in T mutable (not readonly).
For example
interface Todo {
readonly title: string
readonly description: string
readonly completed: boolean
}
type MutableTodo = Mutable<Todo> // { title: string; description: string; completed: boolean; }
Change the following code to make the test cases pass (no type check errors).
type Mutable<T extends object> = {
-readonly [K in keyof T]: T[K];
};How it works:
T to object to ensure only object and array types are accepted (rejecting primitives like string or number, as shown in the error test cases)K in T with keyof T-readonly modifier prefix removes the readonly attribute from each property, which is the inverse of adding readonly (or +readonly)T[K] is preserved as-is, meaning this is a shallow operation -- nested objects retain their original readonly statusAn alternative using the built-in Readonly for context:
// Readonly adds the modifier:
type Readonly<T> = { readonly [K in keyof T]: T[K] };
// Mutable removes it (the exact inverse):
type Mutable<T extends object> = { -readonly [K in keyof T]: T[K] };This challenge helps you understand the readonly modifier and mapped type modifier removal syntax, and how to apply these concepts in real-world scenarios.
This challenge is originally from here.
Be 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