Skip to content

Utility Type

Use built-in utility type like Omit, Partial, Pick, etc.

  • Code reusability: They provide ready-made type transformations that you don't need to reinvent, saving development time.
  • Type safety: They ensure consistent type transformations following TypeScript's best practices, reducing type-related bugs.
  • Readability: Using standard utility types like Partial<T> or Pick<T, K> makes your code more understandable to other TypeScript developers.
  • Maintainability: They reduce the amount of custom type manipulation code, making your codebase easier to maintain.

https://www.typescriptlang.org/docs/handbook/utility-types.html

🚨 DON’T

type User = {
    id: number;
    name: string;
    email: string;
    age: number;
};

// Repeating fields manually
type CreateUser = {
    name: string;
    email: string;
    age: number;
};

// Optional fields written by hand
type UpdateUser = {
    name?: string;
    email?: string;
    age?: number;
};

// Redefining subset types
type UserPreview = {
    id: number;
    name: string;
};

✅ DO

type User = {
    id: number;
    name: string;
    email: string;
    age: number;
};

// Omit to exclude fields
type CreateUser = Omit<User, "id">;

// Partial to make fields optional
type UpdateUser = Partial<Omit<User, "id">>;

// Pick to select specific fields
type UserPreview = Pick<User, "id" | "name">;

// Readonly for immutable data
type ReadonlyUser = Readonly<User>;

// Record for mapping keys to a type
type UserRole = "admin" | "editor" | "viewer";
type RolePermissions = Record<UserRole, string[]>;