typestar

Mapped types in TypeScript

Building a new type by walking another's keys.

interface Settings {
  theme: string;
  volume: number;
}

type Nullable<T> = { [K in keyof T]: T[K] | null };
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

type MaybeSettings = Nullable<Settings>;
type SettingGetters = Getters<Settings>;

const blank: MaybeSettings = { theme: null, volume: null };

How it works

  1. [K in keyof T] iterates every property.
  2. The value type can be transformed as it maps.
  3. as with a template literal renames the keys.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
335
Tokens
101
Three-star pace
110 tpm

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

Type this snippet

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

← Previous Next →