Type aliases for objects and string unions in TypeScript
7 Type aliases for shapes you use more than once
fairCreate an alias for an object shape and another for a small set of allowed strings. Use both, and show what the alias bought you compared with writing the shape out each time.
Stuck? Three hints, smallest first
- 1.
type Name = ...creates an alias. It is a new name for a type, not a new type. - 2. An alias can name a union of string literals, which is how you model a fixed set of options.
- 3. The payoff is one place to change. Add a field to the alias and every use of it is checked again.
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)}`)
);
}
type Tier = 'economy' | 'luxury';
type Booking = {
reference: string;
seats: number;
tier: Tier;
};
function priceOf(booking: Booking): number {
const perSeat = booking.tier === 'luxury' ? 18000 : 12000;
return booking.seats * perSeat + 200;
}
function describe(booking: Booking): string {
return `${booking.reference}: ${booking.seats} ${booking.tier} seat(s)`;
}
const one: Booking = { reference: 'BK-0001', seats: 2, tier: 'economy' };
const two: Booking = { reference: 'BK-0002', seats: 1, tier: 'luxury' };
// A tier outside the two allowed strings is rejected:
// const bad: Booking = { reference: 'BK-3', seats: 1, tier: 'first' };
// ^ not assignable to Tier
console.log(describe(one), '->', priceOf(one));
console.log(describe(two), '->', priceOf(two));
test('economy price', priceOf(one), 24200);
test('luxury price', priceOf(two), 18200);
test('description', describe(two), 'BK-0002: 1 luxury seat(s)');
Output
Two jobs, one keyword. type Booking names a shape so three functions can agree on it. type Tier names a closed set, which is stronger than string: a typo like 'lux' is caught at the point you write it. Prefer a union of literals over an enum for this; it needs no runtime code.