Optional chaining is an attempt to provide a imperative replacement for single method (map()) of single Monad (Maybe). The attempt is quite clunky, it makes code less verbose but harder to read, compose and refactor.
I've not used optional chaining in TypeScript, my opinion is based on using it in Kotlin.
I am Software Developer, currently interested in static type languages (TypeScript, Elm, ReScript) mostly in the frontend land, but working actively in Python also. I am available for mentoring.
The thing is that optional chaining in really only syntax sugar on doing ifs, and in particular - if (x!== null && x!==undefined). The fact that you can chain object property getters (dots) can be viewed as more chain,flatMap, where every getter gives you x | undefined and the next getter works on x. But its not a Monad as it has no map, and you really cannot use any function in this chain outside of mentioned property getters. So in reality it can give you partially what Maybe can give, but in very limited scope, and the basement is not on any monadic abstractions, but standard ifing.
Top comments (3)
Disclaimer: all written below is just my opinion.
Optional chaining is an attempt to provide a imperative replacement for single method (
map()
) of single Monad (Maybe
). The attempt is quite clunky, it makes code less verbose but harder to read, compose and refactor.I've not used optional chaining in TypeScript, my opinion is based on using it in Kotlin.
Hi Sergiy,
thank you for the comment.
The thing is that optional chaining in really only syntax sugar on doing ifs, and in particular -
if (x!== null && x!==undefined)
. The fact that you can chain object property getters (dots) can be viewed as more chain,flatMap, where every getter gives youx | undefined
and the next getter works onx
. But its not a Monad as it has nomap
, and you really cannot use any function in this chain outside of mentioned property getters. So in reality it can give you partially what Maybe can give, but in very limited scope, and the basement is not on any monadic abstractions, but standard ifing.That is exactly my point - optional chaining is a imperative construct attempting to replace functional style in some quite narrow scope.