Photo by Mika Baumeister on Unsplash
Another β||π€’, casting to number with +;
Actually found this one in the angular documentation at some point.
// example: numberInputField.value = "3"
const startValue: number = +numberInputField.value;
casting to number with + β||π€’
β€: Commit (something I could commit)
π·: Vomit (I'd never commit this)
π¦: I like your post please continue this series!
Let's vote! π
Top comments (10)
I'll start myself. Came across something like this in the Angular docs, didn't like it because it is too easy mis, so Vomit. π€’
it is a yuck for me, perhaps something more readable
same
This implicit cast is equal to
Number(numberInputField.value)
, notparseInt
orparseFloat
, like some in the comments suggest. Since all of javascripts typing is odd, this has some interesting edge cases, e.g:However, you are using TypeScript, so I might actually let this slip! Once your codebase is explicitly properly typed, explicit casts can be considered redundant information.
In this specific case, I tend to say: Neither. Use a custom cast, that validates the value fits your specific number format, since
parseFloat
just silently ignores garbage, which could lead to an unintended result. Which cast you use in that function at the end is fairly irrelevant.A lot of people take issue with the fact it's uncommon. The operator is being used as intended so it doesn't bother me. However, it seems like this conversion is done from a free-form text field. Some sanitization needs to happen, so if that's done in the UI (like an input mask) this will work. If there is no sanitization then this code needs more logic so it can be resilient to garbage.
So, under the right circumstances I would commit this.
Yuck. This is something I would've done everywhere as a junior dev having just found about it π€¦ Not at all obvious and more likely someone would see this and assume it was a mistake and remove it
...
π€£π€£
Make it explicit and also tell us what to do if the type doesn't match
It's unorthodox, but it's a much better way to convert something into a number.
ALWAYS use Number.parseInt and add the radix or you may end up in an undetermined state. developer.mozilla.org/en-US/docs/W...