HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptModeratepending

TypeScript utility types cheatsheet — Pick, Omit, Partial, and beyond

Submitted by: @anonymous··
0
Viewed 0 times
PickOmitPartialRequiredReadonlyRecordutility types
nodejsbrowser

Problem

Need to transform existing TypeScript types: make fields optional, pick specific fields, omit sensitive fields, make all fields required, or create read-only versions. Rewriting interfaces is tedious and error-prone.

Solution

Built-in and custom utility types for common type transformations. Includes practical examples for API responses, form state, and database models.

Code Snippets

Built-in and custom utility types for type transformations

interface User {
  id: string;
  name: string;
  email: string;
  password: string;
  role: 'admin' | 'user';
  createdAt: Date;
}

// Pick: select specific fields
type UserPreview = Pick<User, 'id' | 'name'>;
// { id: string; name: string }

// Omit: remove specific fields
type PublicUser = Omit<User, 'password'>;
// everything except password

// Partial: all fields optional
type UserUpdate = Partial<Omit<User, 'id' | 'createdAt'>>;
// { name?: string; email?: string; password?: string; role?: ... }

// Required: all fields required
type StrictUser = Required<UserUpdate>;

// Readonly: all fields immutable
type FrozenUser = Readonly<User>;

// Record: map keys to values
type RolePermissions = Record<User['role'], string[]>;
// { admin: string[]; user: string[] }

// Custom: make specific fields optional
type OptionalFields<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type CreateUser = OptionalFields<User, 'id' | 'createdAt'>;
// id and createdAt are optional, rest required

// Custom: make specific fields required
type RequireFields<T, K extends keyof T> = T & Required<Pick<T, K>>;
type VerifiedUser = RequireFields<Partial<User>, 'id' | 'email'>;
// id and email required, rest optional

// Extract/Exclude for unions
type AdminRole = Extract<User['role'], 'admin'>; // 'admin'
type NonAdmin = Exclude<User['role'], 'admin'>;   // 'user'

Revisions (0)

No revisions yet.