Created
April 8, 2025 15:39
-
-
Save nikoheikkila/92f889a15806e1427fc70d7506882c26 to your computer and use it in GitHub Desktop.
A polymorphism example with classes in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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