Borislav Hadzhiev
Tue Feb 15 2022·2 min read
Photo by Rodion Kutsaev
Use the Omit
utility type to override the type of an interface property,
e.g.
interface SpecificLocation extends Omit<Location, 'address'> {address: newType}
.
The Omit
utility type constructs a new type by removing the specified keys
from the existing type.
interface Location { address: string; x: number; y: number; } interface SpecificLocation extends Omit<Location, 'address'> { address: { country: string; city: string; street: string; }; } const example: SpecificLocation = { x: 5, y: 10, address: { country: 'Chile', city: 'Santiago', street: 'Example street 123', }, };
You can also create a Type instead of an interface when overriding the type of the specific property.
interface Location { address: string; x: number; y: number; } type SpecificLocation = Omit<Location, 'address'> & { address: { country: string; city: string; street: string; }; }; const example: SpecificLocation = { x: 5, y: 10, address: { country: 'Chile', city: 'Santiago', street: 'Example street 123', }, };
If you need to override the type of multiple properties on the interface, use a
pipe |
symbol to separate the types when passing them to the
Omit
utility type.
interface Location { address: string; x: number; y: number; } interface SpecificLocation extends Omit<Location, 'address' | 'x' | 'y'> { address: { country: string; city: string; street: string; }; x: string; y: string; } const example: SpecificLocation = { x: '5', y: '10', address: { country: 'Chile', city: 'Santiago', street: 'Example street 123', }, };
The first type we pass to the Omit
utility type is the type, from which we
will omit one or more keys to construct a new type.
It is very important to exclude the type before overriding it, because if you try to directly override the type of the property on the interface, you would get an error: "Interface X incorrectly extends interface Y".
interface Location { address: string; x: number; y: number; } // ⛔️ Error: Interface 'SpecificLocation' incorrectly extends interface 'Location'. // Types of property 'x' are incompatible. interface SpecificLocation extends Location { x: string; }
By using the Omit
utility type we are able to get around this, by creating an
intermediary type, on which the property does not exist.
In essence, instead of overriding the type of the specific property on the interface: