How to use the Omit keyword in TypeScript

In TypeScript, we often need to create a new type similar to an existing type but with specific properties removed. For instance, consider the Car and CarWithoutColor objects shown below.

Two objects with similar properties
Two objects with similar properties

If we have already created the type for the Car object, we can easily duplicate it and remove the color property as follows:

type Car = {
make: string
model: string
year: number
color: string
}
type CarWithoutColor = {
make: string
model: string
year: number
}

Some issues with this implementation are as follows:

  • If we change to the Car type, we have to remember to make the same change to the CarWithoutColor type and other duplicated types.
  • If we have multiple similar but not identical types, it can be hard to keep track of which type has which properties.
  • It makes the code harder to read and understand.

TypeScript provides a utility type called Omit to help facilitate this transformation while fixing the issues listed above.

The Omit keyword creates a new type by omitting one or more properties from an existing type.

Syntax

The syntax for the Omit keyword is as follows:

type NewType = Omit<ExistingType, 'PropertyName1' | 'PropertyName2' | ...>

In this syntax, NewType is the name of the new type we are creating, ExistingType is the name of the type we are modifying, and PropertyName1, PropertyName2, etc., are the names of the properties we want to exclude from the new type.

Let’s return to our Car and CarWithoutColor examples. We can use the Omit keyword as follows:

type Car = {
make: string
model: string
year: number
color: string
}
type CarWithoutColor = Omit<Car, "color">
/**
* {
* make: string
* model: string
* year: number
* }
*/
// To omit multiple properties
type CarWithoutColorAndYear = Omit<Car, "color" | "year">
/**
* {
* make: string
* model: string
* }
*/

The CarWithoutColor type derives from Car and omits the color property, while the CarWithoutColorAndYear type derives from Car and omits color and year properties.

Conclusion

To summarize, the Omit keyword is a powerful TypeScript feature that allows us to build new types by removing properties from existing types. It is a valuable tool to have in our toolkit when dealing with large-scale TypeScript projects.

Free Resources