snippettypescriptModeratepending
TypeScript utility types -- Pick, Omit, Partial, Required deep dive
Viewed 0 times
PickOmitPartialRequiredReadonlyExtractExcludeReturnType
typescriptnodejs
Problem
Need to derive new types from existing ones without duplicating definitions. Common operations: make fields optional, select subset, exclude fields.
Solution
TypeScript built-in utility types transform existing types. Combine them for complex transformations.
Code Snippets
Utility types for type transformation
interface User {
id: string;
name: string;
email: string;
role: 'admin' | 'user';
createdAt: Date;
}
// Pick: select fields
type UserPreview = Pick<User, 'id' | 'name'>;
// Omit: exclude fields
type CreateUser = Omit<User, 'id' | 'createdAt'>;
// Partial: all optional
type UpdateUser = Partial<Omit<User, 'id'>>;
// Required: all required
type CompleteUser = Required<User>;
// Combine: required ID + partial rest
type PatchUser = Pick<User, 'id'> & Partial<Omit<User, 'id'>>;
// Extract/Exclude on unions
type AdminRole = Extract<User['role'], 'admin'>; // 'admin'
type NonAdmin = Exclude<User['role'], 'admin'>; // 'user'
// Custom: DeepPartial
type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
};
// ReturnType: extract function return type
type Config = ReturnType<typeof getConfig>;Revisions (0)
No revisions yet.