Union of interfaces in TypeScript
3 Two shapes, and a union of them
fairDefine an interface for a car with a make and model. Define a second shape for a bus that adds a payload capacity. Then make a type that is either one, and write a function that handles both safely.
Stuck? Three hints, smallest first
- 1. Reading a property that only one member of the union has is an error until you check for it.
- 2.
'payloadCapacity' in vehiclenarrows the union to the member that has that key. - 3. The alternative is a shared literal field, often called
kind, which is the discriminated-union pattern.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
interface Car {
make: string;
model: string;
}
type Bus = {
make: string;
model: string;
payloadCapacity: number;
};
type Vehicle = Car | Bus;
function describe(vehicle: Vehicle): string {
const base = `${vehicle.make} ${vehicle.model}`;
// vehicle.payloadCapacity is not readable yet: a Car has no such key.
if ('payloadCapacity' in vehicle) {
return `${base}, carries ${vehicle.payloadCapacity}kg`;
}
return `${base}, a car`;
}
const car: Car = { make: 'Toyota', model: 'Corolla' };
const bus: Bus = { make: 'Toyota', model: 'Coaster', payloadCapacity: 400 };
console.log(describe(car));
console.log(describe(bus));
// The tidier long-term shape: give each member a tag.
type Tagged =
| { kind: 'car'; make: string }
| { kind: 'bus'; make: string; payloadCapacity: number };
function describeTagged(v: Tagged): string {
switch (v.kind) {
case 'car': return `${v.make}: a car`;
case 'bus': return `${v.make}: carries ${v.payloadCapacity}kg`;
}
}
console.log(describeTagged({ kind: 'bus', make: 'Toyota', payloadCapacity: 400 }));
test('car description', describe(car), 'Toyota Corolla, a car');
test('bus description', describe(bus), 'Toyota Coaster, carries 400kg');
test('tagged union', describeTagged({ kind: 'car', make: 'Kia' }), 'Kia: a car');
Output
Both narrowing styles work, and the second scales better. With a kind tag, a switch covers every case and TypeScript can tell you when you have missed one. With the in operator you are inspecting shapes, which gets fragile once two members share a key.