- 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
Last active
August 26, 2016 08:01
-
-
Save OliverJAsh/8008bd442a13a10202c06d3d28746775 to your computer and use it in GitHub Desktop.
Option vs vanilla strict null checking
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
// 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment