typestar

Adding and removing modifiers in TypeScript

A mapped type can add or strip readonly and optional.

interface Step {
  readonly idx: number;
  title: string;
  stars?: number;
}

type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type AllOptional<T> = { [K in keyof T]+?: T[K] };
type AllRequired<T> = { [K in keyof T]-?: T[K] };

const mutable: Mutable<Step> = { idx: 0, title: "Mapped types" };
mutable.idx = 1; // allowed: readonly was stripped

const patch: AllOptional<Step> = {};
const complete: AllRequired<Step> = { idx: 2, title: "Modifiers", stars: 3 };

console.log(mutable.idx, Object.keys(patch).length, complete.stars);

How it works

  1. +? adds optional, -? removes it.
  2. -readonly strips the modifier the source had.
  3. That is exactly how Partial and Required are defined.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
530
Tokens
163
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 89 seconds.

Type this snippet

Step 3 of 3 in Mapped types, step 6 of 12 in Type-level programming.

← Previous Next →