21 comments

[ 2.6 ms ] story [ 40.3 ms ] thread
In general, I agree. You don’t want silent failures. They’re awful and hard to reason about.

> By doing this, you're opening up for the possibility of showing a UI where the name is "". Is that really a valid state for the UI?

But as a user, if I get a white screen of death instead of your program saying “Hi, , you have 3 videos on your watchlist” I am going to flip out.

Programmers know this so they do that so that something irrelevant like my name doesn’t prevent me from actually streaming my movies.

I can see this.

I learned from a friend to use Zod to check for process.env. I refined it a bit and got:

```

const EnvSchema = z.object({

  NODE_ENV: z.enum(['development', 'production', 'staging']),

  DATABASE_URL: z.string(),

  POSTHOG_KEY: z.string(),
});

export type AlertDownEnv = z.infer<typeof EnvSchema>;

export function getEnvironments(env: Record<string, string>): AlertDownEnv { return EnvSchema.parse(env); }

```

Then you can:

```

const env = getEnvironments(process.env);

```

`env` will be fully typed!

Definitely, I need to do some improvements in my frontend logic!

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.

> 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.

It seems Rust's unwrap is the exact opposite of ?? "". It throws an error instead of using a fallback value, which is exactly what the author suggests instead of using ?? "".
Author here. I believe I did a poor job of explaining what I meant by this sentence in the article. Sorry about that.

As you, and many others, have pointed out, `?? ""` does not do what `.unwrap` does. `unwrap_or_default` would have been a better comparison for what it actually does. What I tried, and failed, to communicate, was that both can be used to "ignore" the unwanted state, `None` or `undefined`.

I guess the rust equivalent to what I would like to see is `nullable_var?`, and not unwrap as that will panic. That would be equivalent to the `?? throw new Error` feature mentioned further up in the comments.

It’s a feature of the language that’s totally fine to use as much as needed. it’s not a quick n dirty fix.

Don’t listen to those opinionated purists that don’t like certain styles for some reason (probably because they didn’t have that operator when growing up and think it’s a hack)

He lost me at the first example:

```ts user?.name ?? "" ```

The issue isn't the nullish coalescing, but trying to treat a `string | null` as a string and just giving it a non-sense value you hope you'll never use.

You could have the same issue with `if` or `user?.name!`.

Basically seems the issue is the `""`. Maybe it can be `null` and it should be `NA`, or maybe it shouldn't be `null` and should have been handled upstream.

This post and everyone defending this is absolutely crazy

Is this a kink? You like being on call?

You think your performance review is going to be better because you fixed a fire over a holiday weekend or will it be worse when the post mortem said it crashed because you didn’t handle the event bus failing to return firstName

Early errors are good, but I think the author overstates the importance of filtering out empty strings

---

I disagree that erroring out when the app doesn't have ALL the data is the best course of action. I imagine it depends a bit on the domain, but for most apps I've worked on it's better to show someone partial or empty data than an error.

Often the decision of what to do when the data is missing is best left up the the display component. "Don't show this div if string is empty", or show placeholder value.

---

Flip side, when writing an under the hood function, it often doesn't matter if the data is empty or not.

If I'm aggregating a list of fooBars, do I care if fooBarDisplayName is empty or not? When I'm writing tests and building test-data, needing to add a value for each string field is cumbersome.

Sometimes a field really really matters and should throw (an empty string ID is bad), but those are the exception and not the rule.

I keep wondering about a type system where you can say something like "A number greater than 4" or "A string of length greater than 0" or "A number greater than the value of $othernum". If you could do that, you could push so much of this "coping" logic to only the very edge of your application that validates inputs, and then proceed with lovely typesafe values.
I use this operator all the time in a similar but not quite the same way:

<input type=“text” defaultValue={user.email ?? “”}>

The user is an entity from the DB, where the email field is nullable, which makes perfect sense. The input component only accepts a string for the defaultValue prop. So you coalesce the possible null to a string.

(comment deleted)
The problem I have when writing JS/TS is that asserting non-null adds verbosity:

Consider the author’s proposed alternative to ‘process.env.MY_ENV_VAR ?? “”’:

    if (process.env.MY_ENV_VAR === undefined) {
     throw new Error("MY_ENV_VAR is not set")
    }
That’s 3 lines and can’t be in expression position.

There’s a terser way: define an ‘unwrap’ function, used like ‘unwrap(process.env.MY_ENV_VAR)’. But it’s still verbose and doesn’t compose (Rust’s ‘unwrap’ is also criticized for its verbosity).

TypeScript’s ‘!’ would work, except that operator assumes the type is non-null, i.e. it’s (yet another TypeScript coercion that) isn’t actually checked at runtime so is discouraged. Swift and Kotlin even have a similar operator that is checked. At least it’s just syntax so easy to lint…

(comment deleted)
> I've come to see this ubiquitous string of symbols, ?? "", as the JS equivalent to .unwrap() in Rust

Isn't this more like `unwrap_or`?

I cannot tell if the author would agree with this, but here’s my take:

There’s nothing wrong with using the ?? operator, even liberally. But in cases where 1) you don’t think the left side should be undefinable at all or 2) the right side is also an invalid value, you’re better off with an if-statement and handling the invalid case explicitly.

But I’ve used ?? thousands of times in my code in ways unrelated to 1) and 2).

Trivial example:

const numElements = arr?.length ?? 0

IMO this is fine if it’s not an important distinction between an array not existing and the array being empty, and gives you an easier to work with number type.

I definitely do agree with this! It's a very helpful operator in a lot of cases. I think the two cases you point out are prime examples of cases where I would prefer _not_ to encounter them.