constgetStyle = (el: HTMLElement, rule: string) =>el.style[rule]; constbar = document.querySelector('.bar'); letcolor: string; if (bar != null) { letpossibleColor = getStyle(bar, 'color'); if (possibleColor !== null) { color = possibleColor; } else { color = 'black'; } }
(Imagine in this example that there were more than two options: the
simplifying workarounds you commonly use to make this terser in JS, like the
ternary operator or the short-circuiting || or ?? operators, eventually
become very confusing with more complicated flows.)
We can work around this with Maybe, always wrapping each layer in
Maybe.of invocations, and this is somewhat better:
With wrapReturn, though, you can create a transformed version of a function
once and then be able to use it freely throughout your codebase, always
getting back a Maybe:
Transform a function from a normal JS function which may return
null
orundefined
to a function which returns aMaybe
instead.For example, dealing with the
Document#querySelector
DOM API involves a lot of things which can benull
:(Imagine in this example that there were more than two options: the simplifying workarounds you commonly use to make this terser in JS, like the ternary operator or the short-circuiting
||
or??
operators, eventually become very confusing with more complicated flows.)We can work around this with
Maybe
, always wrapping each layer inMaybe.of
invocations, and this is somewhat better:With
wrapReturn
, though, you can create a transformed version of a function once and then be able to use it freely throughout your codebase, always getting back aMaybe
: