Skip to content

Instantly share code, notes, and snippets.

@JonathanLorimer
Last active June 3, 2020 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathanLorimer/717e74c5d14e7ac002a18a3e31f48295 to your computer and use it in GitHub Desktop.
Save JonathanLorimer/717e74c5d14e7ac002a18a3e31f48295 to your computer and use it in GitHub Desktop.
const productType = { a: 3, b: "hello", c: false }
// this has the implied type data ProductType = { a :: Number, b :: String, c :: false }
// even if javascript doesn't demand that we think about it, it matters
// as demonstrated by the below function which IMPLICITLY expects that type signature
const repeatWord = ({a, b, c}) => b + (c ? " " : "/n") + (a <= 0 ? "" : repeatWord({a: a - 1, b, c})
// if you give the above function the wrong 'type' you will get unexpected behaviour
// rather than resulting in a type error you will get either a runtime error or an unexpected return value
// Similarly you might have this
const sum1 = "hello"
const sum2 = 5
const sum3 = false
// and you might want a function to accept any of these and behave differently depending
// if you use the naive implementation above it can be very hard to distinguish the types
// especially if you throw a javascript null in there which has strange type characteristics
// like being equal to an object etc.
// instead you want to use the discriminated union pattern like below
const goodSum1 = {tag: 'sum1', content: "hello"}
const goodSum2 = {tag: 'sum2', content: 5 }
const goodSum3 = {tag: 'sum3', content: false }
// now it is trivial to check which case you have and handle it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment