Last active
July 30, 2021 00:25
-
-
Save matthewoestreich/62b8d2ee6ee42ec2de7affffe4b95574 to your computer and use it in GitHub Desktop.
House class with rooms
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
/** | |
* This code would live inside the library. | |
*/ | |
class House { | |
// Private | |
#rooms: Array<Room> = []; | |
getRooms(): Array<Room> { | |
return this.#rooms; | |
} | |
addRoom(room: Room): void { | |
this.#rooms.push(room); | |
} | |
} | |
interface Room { | |
// Anything that extends this interface HAS to have | |
// a name prop now. | |
name: string; | |
} | |
/** | |
* This code would live in userland (aka how you'd use the library). | |
*/ | |
// Now anywhere that accepts type Room, you can also use Bathroom, | |
// because it's base type is Room. (like in `House.addRoom(room)`) | |
interface Bathroom extends Room { | |
full: boolean; | |
// etc... | |
} | |
interface Bedroom extends Room { | |
sqFt: number; | |
// etc... | |
} | |
const myHouse = new House(); | |
const masterBath: Bathroom = { | |
name: 'master bath', | |
full: true, | |
}; | |
const guestBedroom: Bedroom = { | |
name: 'downstairs guest', | |
sqFt: 300, | |
}; | |
[masterBath, guestBedroom].forEach((roomToAdd) => { | |
// If `roomToAdd` does not satisfy the Room interface | |
// this would throw an error (red squiggly lines). | |
myHouse.addRoom(roomToAdd)); | |
}; | |
console.log( myHouse.getRooms() ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment