Script Valley
TypeScript: Complete Course from Zero
Advanced Types and Real-World PatternsLesson 6.1

Mapped types in TypeScript transforming existing types

mapped type syntax, keyof in mapped types, as clause remapping, built-in mapped types internals, removing modifiers, conditional mapped types

Mapped types

A mapped type iterates over a union of keys and produces a new object type:

type Nullable = {
  [K in keyof T]: T[K] | null;
};

type NullableUser = Nullable;
// { id: number | null; name: string | null; ... }

Removing modifiers

Use -? to remove optional and -readonly to remove readonly:

type Required = { [K in keyof T]-?: T[K]; };
type Mutable  = { -readonly [K in keyof T]: T[K]; };

Key remapping with as

type Getters = {
  [K in keyof T as `get${Capitalize}`]: () => T[K]
};

type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }

Mapped types are the foundation of almost every utility type in TypeScript's standard library. Understanding the [K in keyof T] pattern lets you build custom transformations for any use case.

Up next

Conditional types in TypeScript ternary logic at the type level

Sign in to track progress