Skip to content

Instantly share code, notes, and snippets.

@softwarebygabe
Last active January 12, 2023 02:45
Show Gist options
  • Save softwarebygabe/eea4c054a2d068e163917509a2949cb7 to your computer and use it in GitHub Desktop.
Save softwarebygabe/eea4c054a2d068e163917509a2949cb7 to your computer and use it in GitHub Desktop.
How to write an async class constructor using functional options pattern
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
}
}
}
@softwarebygabe
Copy link
Author

constructor:

const myHouse = new House(
  House.WithRooms(5),
  House.WithFloors(2),
  House.WithMaterial('wood'),
  await House.WithExternalData(),
)

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