DEV Community

Discussion on: What is wrong with optional chaining and how to fix it

Collapse
 
jhoofwijk profile image
jhoofwijk

I mostly agree with Marco. I really do love optional chaining.

For the issue with numbers in conditions: you can always force yourself to only use booleans in conditions using ts-lints strict-boolean-expressions (palantir.github.io/tslint/rules/st...). In my experience it is sometimes nice to have 0 evaluate to false (when checking array length for example) but generally this lint option could prevent quite some hard to find bugs.

Thread Thread
 
macsikora profile image
Pragmatic Maciej

Again the issue is that you need to do the condition on optional and you cannot just execute the expression on it. What is true in Optionals from languages like Swift or Java. Maybe I too much focused on Falsy/Truthy failures. But the point is you always need to do the last check, and this last check is error prone as it was before. Without this check (by mapping) the rules are far more concistent.

Thread Thread
 
vcicmanec profile image
vcicmanec • Edited

You'd need to do it anyway. It's not the fault of optional chaining, it's the fault of dynamic types and truthy-/falsy-ness being baked into the language.

If number of characters is your worry, just use if (z > -1). That will even do a limited type check for you, as objects will always fail.

Thread Thread
 
macsikora profile image
Pragmatic Maciej • Edited

Yes if you talk about the condition issue exactly. The issue is that optional chaining need to be used with previous bad parts baked into language, and because the whole chain checks null | undefined but the last evaluated value put into if will behave by the falsy | Truthy.

But the second is not fully related. The issue is you cannot execute safetly function on the result, you need to always do additional if before, so again it is error prone.