Skip to content

Instantly share code, notes, and snippets.

@fatso83
Created June 21, 2019 08:18
Show Gist options
  • Save fatso83/ccae44b39e41f70d822a06f50ae4788d to your computer and use it in GitHub Desktop.
Save fatso83/ccae44b39e41f70d822a06f50ae4788d to your computer and use it in GitHub Desktop.
Module pattern in TypeScript; having classes doesn't mean you have to use them at all times
// Run this on the playground by copy-pasting: https://www.typescriptlang.org/play
interface Vehicle {
brand: string;
drive(miles: number): void;
getMileage(): void;
}
interface IsPassengerCarrier {
carryingCapacity: number;
}
// marker interface
interface PublicTransportVehicle extends Vehicle, IsPassengerCarrier {}
function Car(brand:string): Vehicle{
const _brand = brand;
let milesDriven = 0;
return {
brand,
drive(miles) {
milesDriven += miles;
},
getMileage() {
return milesDriven;
}
}
}
function Bus(brand:string, carryingCapacity:number): PublicTransportVehicle {
const _car = Car(brand);
return { ..._car, carryingCapacity};
}
const dodge = Car("Dodge Ram");
const doubleDecker = Bus("East Lancashire Coachbuilders‎", 100);
const vehicles = [dodge, doubleDecker];
dodge.drive(50);
dodge.drive(50);
doubleDecker.drive(300)
let output = "";
for (let vehicle of vehicles) {
output += (`${vehicle.brand} has a mileage of ${vehicle.getMileage()}\n`);
}
alert(output);
@fatso83
Copy link
Author

fatso83 commented Jun 25, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment