Is this a weakness in the type definition? If we're sure the value cannot be undefined, then why doesn't the type reflect that? Why not cast to a non-undefined type as soon as we're sure (and throw if it is not)? At least that would document our belief in the value state. I may not understand.
Abuse of the nullish coalescing operator in JS/TS
11–20 of 70 posts
Re: Abuse of the nullish coalescing operator in JS/TS
#12Re: Abuse of the nullish coalescing operator in JS/TS
#13Should throw expressions ( https://github.com/tc39/proposal-throw-expressions ) ever make it into the JavaScript standard, the example could be simplified to: const env_var = process.env.MY_ENV_VAR ?? throw new Error("MY_ENV_VAR is not set");
so like assert(process.env.MY_ENV_VAR) but in a less readable oneliner?
Null chaining is also a common pattern across most languages and is generally seen as readable
Re: Abuse of the nullish coalescing operator in JS/TS
#14Should throw expressions ( https://github.com/tc39/proposal-throw-expressions ) ever make it into the JavaScript standard, the example could be simplified to: const env_var = process.env.MY_ENV_VAR ?? throw new Error("MY_ENV_VAR is not set");
so like assert(process.env.MY_ENV_VAR) but in a less readable oneliner?
Re: Abuse of the nullish coalescing operator in JS/TS
#15It's funny you bring this up because people opposed to `.unwrap()` usually mention methods like `.unwrap_or` as a "better" alternative, and that's exactly the equivalent of `??` in Rust.
Re: Abuse of the nullish coalescing operator in JS/TS
#16Earlier quoted context omitted.
Exactly, something like a name missing shouldn't cause the app to completely error out for the user.
Yes it should, because hopefully errors are logged and reported and can be acted upon. Missing name doesn’t.
Re: Abuse of the nullish coalescing operator in JS/TS
#17Earlier quoted context omitted.
Yes it should, because hopefully errors are logged and reported and can be acted upon. Missing name doesn’t.
Why not both?
tldr: undefined constants were treated as a string (+ a warning), so `$x = FOO` was `$x = "FOO"` + a warning if `FOO` was not a defined constant. Thankfully this feature was removed in PHP 8.
Re: Abuse of the nullish coalescing operator in JS/TS
#18Earlier quoted context omitted.
Exactly, something like a name missing shouldn't cause the app to completely error out for the user.
Yes it should, because hopefully errors are logged and reported and can be acted upon. Missing name doesn’t.
Re: Abuse of the nullish coalescing operator in JS/TS
#19> Personally, I've come to see this ubiquitous string of symbols, ?? "", as the JS equivalent to .unwrap() in Rust It's funny you bring this up because people opposed to `.unwrap()` usually mention methods like `.unwrap_or` as a "better" alternative, and that's exactly the equivalent of `??` in Rust.