Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Last active August 26, 2016 08:01
Show Gist options
  • Save OliverJAsh/8008bd442a13a10202c06d3d28746775 to your computer and use it in GitHub Desktop.
Save OliverJAsh/8008bd442a13a10202c06d3d28746775 to your computer and use it in GitHub Desktop.
Option vs vanilla strict null checking
// findPersonWithName = string => Person | undefined;
// findParentForPerson = Person => Person | undefined;
// isOver50 = Person => boolean;
// isSubscribed = Person => boolean;
// Without Options
// In TS1 this is not type safe, in TS2 it is
const person = findPersonWithName('bob')
const parent = person !== undefined ? findParentForPerson(person) : undefined;
const parentOver50 = parent !== undefined ? (isOver50(parent) ? parent : undefined) : undefined;
const parentIsSubscribed = parentOver50 !== undefined ? isSubscribed(parentOver50) : undefined;
const isBobParentSubscribed = parentIsSubscribed !== undefined ? personIsSubscribed : false;
// Options
const isBobParentSubscribed = findPersonWithName('bob')
.flatMap(findParentForPerson)
.filter(isOver50)
.map(isSubscribed)
.getOrElse(false)
  • Both equally as type safe in TS2
  • Chaining of Option is convenient and makes for concise code
  • Isolating null checks in Options means you're safe from coercion errors (e.g. const x = 0; const derivedY = x ? x + 1 : 1;x is falsy)
  • Option forces you to handle failure case
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment