Hack Frontend Community

Utility Type Omit in TypeScript — Omit TypeScript

Omit is a utility type in TypeScript that allows excluding specific properties from an already existing type or interface. It creates a new type by removing from original field list those you specified.


Syntax

Omit<T, K>
  • T — original type (or interface) from which you want to exclude properties.
  • K — union of keys you want to remove from T.

Omit removes named fields and leaves everything else unchanged.


When to use Omit?

  • If you need to exclude unnecessary properties from object.
  • For API responses where sensitive data needs to be hidden.
  • In React components to pass only needed properties.

Omit Usage Example

Suppose we have a User interface with several fields:

interface User {
  id: number;
  name: string;
  age: number;
  isAdmin: boolean;
}

If in some place of application we want to work with user but don't want to have access to isAdmin, we can use Omit:

type PublicUserData = Omit<User, "isAdmin">;

const userData: PublicUserData = {
  id: 1,
  name: "Alice",
  age: 25,
};

userData.isAdmin = true;
// ❌ Error: property 'isAdmin' is missing in type 'PublicUserData'

  • PublicUserData — contains all User fields except isAdmin.
  • Any attempt to access isAdmin will cause compilation error as this property doesn't exist in new type.

API Example

Often after getting user data from database or external API you want to pass to "frontend" object without some private fields:

interface User {
  id: number;
  name: string;
  email: string;
  passwordHash: string;
  isAdmin: boolean;
}

type SafeUserData = Omit<User, "passwordHash" | "email">;

function getSafeUserData(user: User): SafeUserData {
  const { passwordHash, email, ...rest } = user;
  return rest;
}

const user: User = {
  id: 42,
  name: "Bob",
  email: "bob@example.com",
  passwordHash: "hashed_password",
  isAdmin: false,
};

const safeData = getSafeUserData(user);
// safeData doesn't contain passwordHash and email

In result only id, name and isAdmin are passed outward, while confidential data remains hidden.


Why Omit?

  • Shortened type versions: Allows excluding unnecessary properties to not pass them to some parts of application.
  • Security: Can remove confidential fields (e.g., password, token, isAdmin) for public data representation.
  • Avoiding conflicts: When you need to override some fields, they can first be excluded then added again with needed type.