Last active
January 12, 2023 02:45
-
-
Save softwarebygabe/eea4c054a2d068e163917509a2949cb7 to your computer and use it in GitHub Desktop.
How to write an async class constructor using functional options pattern
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
type Material = 'wood' | 'brick' | 'steel' | |
type HouseOption = (h: House) => void | |
class House { | |
private rooms: number | |
private floors: number | |
private material: Material | |
private externalData: any | |
constructor(...options: HouseOption[]) { | |
// defaults | |
this.rooms = 1 | |
this.floors = 1 | |
this.material = 'wood' | |
this.externalData = null | |
// set the options | |
for (const option of options) { | |
option(this) | |
} | |
} | |
public static WithRooms(roomCount: number): HouseOption { | |
return (h: House): void => { | |
h.rooms = roomCount | |
} | |
} | |
public static WithFloors(floorCount: number): HouseOption { | |
return (h: House): void => { | |
h.floors = floorCount | |
} | |
} | |
public static WithMaterial(material: Material): HouseOption { | |
return (h: House): void => { | |
h.material = material | |
} | |
} | |
public static async WithExternalData(): Promise<HouseOption> { | |
// fetch the external data here (this is just a demonstration, could be any async op) | |
const data = await externalAPI.getData() | |
// now set the data on the class instance | |
return (h: House): void => { | |
h.externalData = data | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
constructor: