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).
interface Todo1 {
title: string
description: string
completed: boolean
meta: {
author: string
}
}
type List = [1, 2, 3]
type cases = [
Expect<Equal<Mutable<Readonly<Todo1>>, Todo1>>,
Expect<Equal<Mutable<Readonly<List>>, List>>,
]
type errors = [
// @ts-expect-error
Mutable<'string'>,
// @ts-expect-error
Mutable<0>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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.