Reputation: 25840
What is the correct/best way to refactor this logic, using nullish operator? -
if (value !== undefined && value !== null && typeof value !== 'object') {
// error, when not null/undefined, it must be an object
}
UPDATE
So far I've tried this one, which seems to be working, though looks a little odd:
if (typeof (value ?? null) !== 'object') {
// error...
}
Would that be a proper equivalent?
P.S. I'm writing this is TypeScript, so browsers compatibility doesn't concern me.
Upvotes: 0
Views: 651
Reputation: 7220
Although your existing implementation example will work, JavaScript's typeof
function has a longstanding history of causing confusion in the case of typeof(null)
returning 'object'
. One of your most important considerations in refactoring code will always be the maintainability of your code, and any likely source of confusion is likely to reduce maintainability.
If someone were to look at this code right now, particularly any developer who is inexperienced with JavaScript or has never run into the typeof(null)
quirk, they would assume that your code is looking for all non-object types, including the values of null
and undefined
rather than excluding them.
Additionally, although current JavaScript standards are unlikely to change the behavior of typeof(null)
to avoid breaking existing code, there's no absolute guarantee that this behavior will never change. There's especially no guarantee that TypeScript itself won't change this behavior to be more intuitive and transcompile down to a different JavaScript equivalent.
You're far better off avoiding confusion in your code as well as potentially future compatibility breaking updates if you modify the default fallback value for your nullish coalescing operation. Specifically, default to {}
which is always guaranteed to be interpreted as an object and will be far less likely to be subject to breaking changes in either JavaScript or TypeScript:
if (typeof (value ?? {}) !== 'object') {
// error...
}
Upvotes: 1