I think shortcuts like the following are fundamentally flawed, at least when dealing with user input.
If (user && user.name) { ...
While it sucks to have to even check for user etc, not checking that it’s truthy, then an object, then checking that the name is the correct type also during runtime, will cause bugs over time.
This type of developer provided shorthand validation is pretty much the cause of all hacks/data breaches currently. It’s more of an attitude or how a developer prioritizes their own wants/needs over maybe a client/end user. Like I mentioned in another comment, checking for more advanced, abusive behavior will make issues with type checking seem basic in comparison.
Will be nice when JS gets the Elvis operator and you’ll be able to do ‘if (typeof user?.name === “string”)’ which will have the added value of type narrowing/interaction with ‘never’ if name is expected to be something else.
I'd say the elvis operator would make things worse, especially wrt the parent post.
The problem isn't that `user && user.username` style validation is verbose, but that it's very error-prone. Making it less verbose just means you'll more likely use it before you reach for a better validation strategy, like a declarative validation library.
This type of developer provided shorthand validation is pretty much the cause of all hacks/data breaches currently. It’s more of an attitude or how a developer prioritizes their own wants/needs over maybe a client/end user. Like I mentioned in another comment, checking for more advanced, abusive behavior will make issues with type checking seem basic in comparison.