Last active
March 22, 2021 21:33
-
-
Save HairyMike/8527ee29f2821052ff88b60a6c2c78af to your computer and use it in GitHub Desktop.
Type aliases and higher order functions with Typescript
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
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