DEV Community

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

Collapse
marcotraspel profile image
Marco Traspel

Sorry that's bs.
You also don't go like
A = 0;
If (a)
....
And say oh that's stupid that 0 is falsy???

Collapse
macsikora profile image
Pragmatic Maciej Author • Edited on

Thank you for the comment. But yes that is almost never what you want. Only in division 0 is kinda problem. In any other operation 0 is fully valid number, and there is no reason why you should not tread it like that. Rules like Falsy - null | undefined and Truthy everything else would be much much cleaner. I always think twice if empty array is T or is F. As string in many languages is represented as Char[] having [] T and '' F has totally no sense.

In the article I wanted to emphasize different thing really - that you cannot compose nicely with positive result of optional chaining and there always needs to be another condition. Again thanks for the comment.

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 Author

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 on

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 Author • Edited on

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.