#2793Medium

Mutable

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.

Challenge Instructions: Mutable

Medium

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).

ChallengeSolution
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>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type Mutable<T extends object> = {
  -readonly [K in keyof T]: T[K];
};

How it works:

An 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.

Share this challenge

Learn the Concepts