Re:Don't Use Booleans
by ivan_gammel on Tuesday July 09, 2024 @05:42AM
(#40914147)
That’s the worst way to define enums. Now you have to make sure your codebase is using the same string literals everywhere and carry the potentially long type definition to every parameter, variable or function return type. And no, compile-time checks won’t cover 100% of cases.
[ Parent
| on HN ]
Re:Don't Use Booleans
by teaearlgraycold on Tuesday July 09, 2024 @12:38PM
(#40918082)
Obviously if this gets reused you need to put it in a central definition.
Re:Don't Use Booleans
by SkyPuncher on Tuesday July 09, 2024 @01:06PM
(#40918365)
The only place I believe this pattern is acceptable is option props in React components.
Otherwise, it becomes an absolute mess of “almost” defined correctly.
Re:Don't Use Booleans
by ivan_gammel on Wednesday July 10, 2024 @06:13PM
(#40932030)
How wouldn’t it be reused? Besides, what will happen if you need to change a constant in the enum from „a“ to „b“? Compiler won’t help you to spot all the places like ˋˋˋif (value == „a“)ˋˋˋ, it will quietly become unreachable in runtime.
Re:Don't Use Booleans
by teaearlgraycold on Wednesday July 10, 2024 @06:22PM
(#40932087)
You underestimate TypeScript. Your example will give a compiler error:
This comparison appears to be unintentional because the types '"a"' and '"b"' have no overlap.(2367)
https://www.typescriptlang.org/play/?#code/MYewdgzgLgBAZiEAu...It's features like these that make Python/Ruby/etc. type-checkers insufficient substitutes for TypeScript.
I think my example wasn't the best. Of course "active" | "inactive" would get reused. But if it's just a little function flag it could easily be a one-off.