1 June 2021

TypeScript's Omit, explained

It will remove fields from a given object type. It's useful in making subsets of an object type.

Rico Sta. Cruz @rstacruz

The TypeScript helper called Omit is really useful! It will remove fields from a given object type. It’s useful in making subsets of an object type.

example.ts
interface Book {
  author: string;
  isbn: string;
  title: string;
}
type SimpleBook = Omit<Book, 'author'>;
// => { isbn: string; title: string; };
Using Omit removes the author field, leaving only isbn and title.

Multiple fields

🤔 What if we want to omit more fields? — Omit can take away more fields by joining many fields with a union type. Here it is removing two fields.

example.ts
interface Book {
  author: string;
  isbn: string;
  title: string;
}
type IsbnOnlyBook = Omit<Book, 'author' | 'title'>;
// => { isbn: string; };
The union ‘author’ | ‘title’ allows omitting two different fields from the interface.

Using with generics

🤔 What if we want to reuse Omit on many things, not just books? — We can use a generic type that we can reuse on types other than Book. How about with a Tweet, for example:

example.ts
interface Book {
  author: string;
  isbn: string;
  title: string;
}
interface Tweet {
  author: string;
  body: string;
}
type NoAuthor<T> = Omit<T, 'author'>;

type AnonymousBook = NoAuthor<Book>;
// => { isbn: string; title: string; }
type AnonymousTweet = NoAuthor<Tweet>;
// => { body: string; }

Pick: the opposite of Omit

The opposite of Omit is Pick, which removes all fields except the ones you want.

example.ts
interface Book {
  author: string;
  isbn: string;
  title: string;
}
type AuthorOnly = Pick<Book, 'author'>
// => { author: string; }

type WithoutAuthor = Omit<Book, 'author'>
// => { isbn: string; title: string; }
type TitleAndAuthorOnly = Pick<Book, 'title' | 'author'>
// => { title: string; author: string; }
Thanks for reading! I'm Rico Sta Cruz, I write about web development and more. Subscribe to my newsletter!