#typescript #types #advanced

Day 21: Mapped Types

Looping over Types

Welcome to Day 21! Yesterday we used Partial. Today we learn how to build Partial from scratch using Mapped Types.

Syntax

A mapped type looks like [Property in Key]: Type.

type OptionsFlags<Type> = {
  [Property in keyof Type]: boolean;
};

It takes all properties in Type and changes their values to boolean.

type FeatureFlags = {
  darkMode: () => void;
  newUserProfile: () => void;
};

type FeatureOptions = OptionsFlags<FeatureFlags>;
// { darkMode: boolean; newUserProfile: boolean; }

Modifiers

You can add or remove ? (optional) and readonly.

Removing Optional (-?)

type Concrete<Type> = {
  [Property in keyof Type]-?: Type[Property];
};

This removes ? from all properties (essentially Required<Type>).

Adding Readonly (+readonly)

type Locked<Type> = {
  readonly [Property in keyof Type]: Type[Property];
};

Challenge for Today

  1. Create a generic type Stringify<T>.
  2. It should take an object and convert all its properties to string.
  3. Test it on a type with numbers and booleans.

See you on Day 22 for Conditional Types!