snippettypescriptTippending
TypeScript utility types cheat sheet
Viewed 0 times
utility typespartialpickomitrecordextractexclude
Problem
Need a quick reference for TypeScript's built-in utility types and when to use each.
Solution
Complete utility types reference:
interface User {
id: number;
name: string;
email: string;
role: 'admin' | 'user';
}
// Partial<T> - All properties optional
type UpdateUser = Partial<User>;
// { id?: number; name?: string; ... }
// Required<T> - All properties required
type CompleteUser = Required<Partial<User>>;
// Readonly<T> - All properties readonly
type FrozenUser = Readonly<User>;
// Pick<T, K> - Select specific properties
type UserPreview = Pick<User, 'id' | 'name'>;
// { id: number; name: string }
// Omit<T, K> - Remove specific properties
type CreateUser = Omit<User, 'id'>;
// { name: string; email: string; role: ... }
// Record<K, V> - Object type with key type K and value type V
type RolePermissions = Record<User['role'], string[]>;
// { admin: string[]; user: string[] }
// Extract<T, U> - Extract types assignable to U
type AdminRole = Extract<User['role'], 'admin'>;
// 'admin'
// Exclude<T, U> - Remove types assignable to U
type NonAdminRole = Exclude<User['role'], 'admin'>;
// 'user'
// NonNullable<T> - Remove null and undefined
type SafeString = NonNullable<string | null | undefined>;
// string
// ReturnType<T> - Get function return type
type FetchResult = ReturnType<typeof fetchUser>;
// Parameters<T> - Get function parameter types
type FetchParams = Parameters<typeof fetchUser>;
// Awaited<T> - Unwrap Promise type
type UserData = Awaited<ReturnType<typeof fetchUser>>;Why
Built-in utility types eliminate the need for custom type manipulations in most cases. Knowing them prevents reinventing the wheel.
Context
TypeScript development - quick reference
Revisions (0)
No revisions yet.