Composition: a car has an engine in TypeScript
4 A car that has an engine, rather than being one
fairWrite an engine class with horsepower and fuel type. Then give a car class an engine as one of its properties, and a method that prints both the car's and the engine's details.
Stuck? Three hints, smallest first
- 1. This is composition: the car has an engine. Nothing extends anything here.
- 2. Let the engine describe itself, and have the car ask it. Do not reach into the engine’s fields from the car.
- 3. Taking the engine as a constructor parameter makes it swappable and testable.
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)}`)
);
}
class Engine {
constructor(
public horsepower: number,
public fuelType: 'diesel' | 'petrol',
) {}
describe(): string {
return `${this.horsepower}hp ${this.fuelType}`;
}
}
class Car {
constructor(
public make: string,
public model: string,
public year: number,
private engine: Engine, // has-a, not is-a
) {}
start(): string {
return `${this.make} ${this.model} is starting`;
}
// The car asks the engine to describe itself rather than reading its fields.
printCarDetails(): string {
return `${this.year} ${this.make} ${this.model} - ${this.engine.describe()}`;
}
}
const diesel = new Engine(120, 'diesel');
const car = new Car('Toyota', 'Coaster', 2019, diesel);
console.log(car.start());
console.log(car.printCarDetails());
// Swapping the engine is easy, because it was passed in.
const stronger = new Car('Toyota', 'Coaster', 2019, new Engine(150, 'diesel'));
console.log(stronger.printCarDetails());
test('engine describes itself', diesel.describe(), '120hp diesel');
test('car details include the engine', car.printCarDetails(), '2019 Toyota Coaster - 120hp diesel');
test('start still works', car.start(), 'Toyota Coaster is starting');
test('a different engine changes the output', stronger.printCarDetails(), '2019 Toyota Coaster - 150hp diesel');
Output
Two habits worth copying. The engine is private, so no caller can reach car.engine.horsepower and tie itself to the engine’s shape. And the car calls engine.describe() instead of formatting the engine’s fields itself, so a change to the engine touches one file.