Back

TypeScript Omit Utility Type

`Omit< T, K >` creates a new type by excluding specified properties (`K`) from a type (`T`). It’s great for hiding sensitive or unnecessary fields.

Basic Example: Removing Sensitive Data

type User = {
    id: number;
    name: string;
    password: string;
    email: string;
  };
  
  // We want to create a type without sensitive 'password' field
  type PublicUser = Omit<User, 'password'>;
  
  const publicUser: PublicUser = {
    id: 1,
    name: "Alice",
    email: "alice@example.com"
  };
  
  // password field is not allowed here
  // publicUser.password = "123"; // Error

Removing the `password` field from `User` creates a safe `PublicUser` type, preventing accidental exposure of sensitive data.

Omitting Multiple Fields

interface Product {
    id: number;
    name: string;
    description: string;
    price: number;
    internalCode: string;
  }
  
  // API response should not expose internalCode and description
  type PublicProduct = Omit<Product, 'internalCode' | 'description'>;
  
  function showProduct(product: PublicProduct) {
    console.log(product.name, product.price);
  }
  
  const product: PublicProduct = {
    id: 101,
    name: "Laptop",
    price: 1500,
  };
  
  showProduct(product);

Exclude `internalCode` and `description` from `Product` to hide unwanted fields in API responses.

Real-World Example: Settings

type FullSettings = {
    darkMode: boolean;
    fontSize: number;
    language: string;
    autoSave: boolean;
  };
  
  type SettingsWithoutAutoSave = Omit<FullSettings, 'autoSave'>;
  
  const settings: SettingsWithoutAutoSave = {
    darkMode: true,
    fontSize: 14,
    language: "en"
  };
  
  console.log(settings);
  // Output: { darkMode: true, fontSize: 14, language: "en" }

Omitting `autoSave` from `FullSettings` produces a type containing only user-changeable settings.

Why Use Omit?

`Omit` improves data privacy, API security, and helps work with only required fields, enhancing code safety and readability.

Back