← Back to TypeScript Course | Chapter 8: Advanced Types | Lesson 14 of 20

Utility Types - Omit

Omit<T, K> creates a new type by removing selected properties from another type. It is useful when certain fields should not be exposed or supplied.

Basic Omit

Omit<T, K> removes the properties named in K while keeping every other property of T intact, effectively the inverse operation of Pick<T, K>. It's especially handy for stripping one or two fields out of an otherwise large, mostly-reusable type.

Example: Basic Omit

typescript
interface User {
  id: number;
  name: string;
  password: string;
}
type PublicUser = Omit<User, "password">;
const u: PublicUser = { id: 1, name: "Ravi" };
console.log(u);

Omit for Input Objects

Omit is useful for creating input types that exclude generated or protected fields — for example removing an auto-generated id from a type before it's used to create a new record.

Example: Omit for Input Objects

typescript
interface User {
  id: number;
  name: string;
}
type NewUser = Omit<User, "id">;
const newUser: NewUser = { name: "Ravi" };
console.log(newUser);

Omit Multiple Properties

Omit can remove several properties at once by supplying a union of keys, such as Omit<User, id | createdAt>, rather than only being able to remove one property at a time.

Example: Omit Multiple Properties

typescript
interface User {
  id: number;
  createdAt: string;
  name: string;
}
type CreateUserInput = Omit<User, "id" | "createdAt">;
const input: CreateUserInput = { name: "Ravi" };
console.log(input);

Omit with Functions

Omit can create precise function parameter types by removing fields that a function doesn't need or shouldn't accept, tightening the function's signature beyond the full original type.

Example: Omit with Functions

typescript
interface Task {
  id: number;
  title: string;
  done: boolean;
}
function createTask(task: Omit<Task, "id" | "done">) {
  console.log("Creating task:", task.title);
}
createTask({ title: "Write code" });

When to Use Omit

Use Omit when a new type should contain almost all of an existing type except for a small, specific number of properties that don't belong in that particular context, such as removing server-generated fields before sending data back to create a new record.

Example: When to Use Omit

typescript
interface Record_ {
  id: number;
  createdAt: string;
  name: string;
}
type NewRecord = Omit<Record_, "id" | "createdAt">;
const r: NewRecord = { name: "Ravi" };
console.log(r);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.