Created
June 21, 2019 08:18
-
-
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
This file contains 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
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Runnable: https://repl.it/@fatso83/Module-Pattern-in-TypeScript