snippettypescriptModeratepending
TypeScript Record and Mapped Type patterns
Viewed 0 times
recordmapped typespartialpickomitrequired
Problem
Need to create type-safe dictionaries, transform object types, or derive types from existing ones.
Solution
Common mapped type patterns:
// Type-safe config from union
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
type LogConfig = Record<LogLevel, boolean>;
// Make all properties optional
type PartialUser = Partial<User>;
// Make all properties required
type RequiredConfig = Required<Config>;
// Pick specific properties
type UserPreview = Pick<User, 'id' | 'name'>;
// Omit specific properties
type CreateUser = Omit<User, 'id' | 'createdAt'>;
// Custom mapped type: make specific keys required
type RequireKeys<T, K extends keyof T> = T & Required<Pick<T, K>>;
type UserWithEmail = RequireKeys<Partial<User>, 'email'>;
// Readonly deep
type DeepReadonly<T> = {
readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};Why
Mapped types let you derive types from existing ones, reducing duplication and keeping types in sync.
Context
TypeScript projects needing type transformations
Revisions (0)
No revisions yet.