Skip to content

Instantly share code, notes, and snippets.

@HairyMike
Last active March 22, 2021 21:33
Show Gist options
  • Save HairyMike/8527ee29f2821052ff88b60a6c2c78af to your computer and use it in GitHub Desktop.
Save HairyMike/8527ee29f2821052ff88b60a6c2c78af to your computer and use it in GitHub Desktop.
Type aliases and higher order functions with Typescript
type Thing = {
shape: Shape,
size: number,
}
enum Shape {
Circle,
Square,
Rectangle,
Triangle,
}
type ThingOption = (thing: Thing) => void;
function WithShape(shape: Shape) {
return function(thing: Thing) {
thing.shape = shape;
}
}
function WithSize(size: number): ThingOption {
return function(thing: Thing) {
if (size < 1) {
throw new Error("size can't be less than 1");
}
thing.size = size
}
}
function NewThing(...options: ThingOption[]): Thing {
let thing: Thing
options.forEach(option => option(thing));
return thing;
}
const thing = NewThing(
WithShape(Shape.Square),
WithSize(3),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment