Skip to content

Instantly share code, notes, and snippets.

@d4vsanchez
Created April 17, 2021 17:16
Show Gist options
  • Save d4vsanchez/743bd534e4611025353fb90fc0e8f3b5 to your computer and use it in GitHub Desktop.
Save d4vsanchez/743bd534e4611025353fb90fc0e8f3b5 to your computer and use it in GitHub Desktop.
An example showing how to create a function that must call its pre-requisites in order to be called, using TypeScript.
// Let's create a class to build a simple Pizza
// Our PizzaBuilder can set:
// 1. Pizza size (required)
// 2. Pizza flavour (required)
// 3. Pizza crust (optional)
// We must make sure that the "cook" function is type-checked and can be called
// only if we have set a size or a flavour.
type PizzaSizes = 'small' | 'medium' | 'large' | 'extra large';
type PizzaFlavour = 'pepperoni' | 'bbq chicken' | 'margherita' | 'vegetarian';
type PizzaCrust = 'classic' | 'cheesy' | 'edge';
type PizzaBuilderType = {
size: PizzaSizes
flavour: PizzaFlavour
crust?: PizzaCrust
};
class PizzaBuilder {
size?: PizzaSizes
flavour?: PizzaFlavour
crust?: PizzaCrust
setSize(size: PizzaSizes): this & Pick<PizzaBuilderType, 'size'> {
return Object.assign(this, { size });
}
setFlavour(flavour: PizzaFlavour): this & Pick<PizzaBuilderType, 'flavour'> {
return Object.assign(this, { flavour });
}
setCrust(crust: PizzaCrust): this & Pick<PizzaBuilderType, 'crust'> {
return Object.assign(this, { crust });
}
cook(this: PizzaBuilderType): object {
return { size: this.size, flavour: this.flavour, crust: this.crust };
}
}
const pepperoniPizza = new PizzaBuilder().setSize('small').setFlavour('pepperoni').cook();
// Uncomment the line below, the type-checker won't let you call the cook() method, as the flavour is missing.
// const invalidPizza = new PizzaBuilder().setSize('small').cook();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment