Write Beautiful JS — with Union Types

Photo by Niko Soikkeli on Unsplash
type Boolean = True | False
type Answer = Yes | No | Undecided
type Answer = Response String | Declined | Undecided
type Maybe a = Just a | Nothingtype Either e a = Left e | Right a
const construct = (type, values) => {
/* construct type value */
}
const Answer = {
Response: (response) => construct('Response', [response]),
Declined: construct('Declined', []),
Undecided: construct('Undecided', [])
}
const answer = Answer.Response('sure thing!')
const declinedAnswer = Answer.Declined
const construct = (type, values) => ({
case: (cases) => cases[type].apply(null, values)
})
let answer = Answer.Response('sure thing!')let answerString = answer.case({
Response: (response) => `I answered: ${response}`,
Declined: () => `I'd rather not say`,
Undecided: () => `I'm still thinking...`
})
console.log(answerString) // prints "I answered: sure thing!"
let answer = {
response: "sure thing!", // null if undecided
declined: false
}
const Step = {
ViewingCart: (items) => construct('ViewingCart', [items]),
ConfirmOrder: (details) => construct('ConfirmOrder', [details]),
ProcessingOrder: construct('ProcessingOrder', []),
SubmittedOrder: construct('SubmittedOrder', []),
CancelledOrder: (reason) => construct('CancelledOrder', [reason])
}

Many languages have trouble expressing data with weird shapes. They give you a small set of built-in types, and you have to represent everything with them. So you often find yourself using null or booleans or strings to encode details in a way that is quite error prone.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store