Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Created April 8, 2025 15:39
Show Gist options
  • Save nikoheikkila/92f889a15806e1427fc70d7506882c26 to your computer and use it in GitHub Desktop.
Save nikoheikkila/92f889a15806e1427fc70d7506882c26 to your computer and use it in GitHub Desktop.
A polymorphism example with classes in Typescript
export abstract class Vehicle {
public abstract wheels: number;
public get name() {
return this.constructor.name;
}
}
export class Bicycle extends Vehicle {
public get wheels() {
return 2;
}
}
export class Car extends Vehicle {
public get wheels() {
return 4;
}
}
export class Truck extends Vehicle {
public get wheels() {
return 18;
}
}
export class VehicleList {
private readonly vehicles: Vehicle[];
public static empty() {
return new VehicleList([]);
}
public add(vehicle: Vehicle) {
this.vehicles.push(vehicle);
return this;
}
public print() {
this.vehicles.forEach((vehicle) => {
console.log(`A ${vehicle.name} has ${vehicle.wheels} wheels.`);
});
}
private constructor(vehicles: Vehicle[]) {
this.vehicles = vehicles;
}
}
function main() {
VehicleList.empty()
.add(new Bicycle())
.add(new Car())
.add(new Truck())
.print();
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment