TypeScript

Mapped Types (Partial/Required/etc)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Mapped types iterate over keys to produce new types. The standard library's `Partial`, `Required`, `Readonly`, `Pick`, `Omit`, `Record` are all one-liners — and you can build your own.
TypeScript
Raw
type User = { id: string; name: string; email: string };

// Deep readonly (recursive)
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};

// Mutable inverse of Readonly
type Mutable<T> = { -readonly [K in keyof T]: T[K] };

// Keep only the keys whose value matches a type
type KeysOfType<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];

type StringKeys = KeysOfType<User, string>;     // 'id' | 'name' | 'email'

// Make some keys optional (the others stay required)
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

type NewUser = PartialBy<User, 'id'>;
// { name: string; email: string; id?: string }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.