We can use Typescript’s Exclude
with types in order to exclude certain members of a type.
Example
If we have a type called Vehicles
in which we wish to exclude vehicles of type ‘SUV’ for example, we would use Exclude
and do the following:
type Vehicles =
| { make: 'BMW', model: '325', type: 'sedan' }
| { make: 'BMW', model: '525', type: 'sedan' }
| { make: 'BMW', model: 'X6', type: 'SUV' };
type sedans = Exclude<Vehicles, { type: 'SUV' }>;
const cars: sedans[] = [
{ make: 'BMW', model: '325', type: 'sedan' },
{ make: 'BMW', model: '525', type: 'sedan' },
];
If we were to include a vehicle of type ‘SUV’ in the array of objects called cars above,Typescript’s compiler would automatically point out that entry as an error.