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.
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: stringmodel: stringyear: numbercolor: string}type CarWithoutColor = {make: stringmodel: stringyear: number}
Some issues with this implementation are as follows:
Car type, we have to remember to make the same change to the CarWithoutColor type and other duplicated types.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.
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: stringmodel: stringyear: numbercolor: string}type CarWithoutColor = Omit<Car, "color">/*** {* make: string* model: string* year: number* }*/// To omit multiple propertiestype 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.
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.