Skip to content(if available)orjump to list(if available)

Abuse of the nullish coalescing operator in JS/TS

robertlagrant

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.

epolanski

You can do it in typescript with branded types:

https://effect.website/docs/schema/advanced-usage/#branded-t...

There is some ceremony around it, but when you do the basic plumbing it's invaluable to import NonEmptyString100 schema to define a string between 1 and 100 chars, and have parsing and error handling for free anywhere, from your APIs to your forms.

It's also a way to say, sure this is a string input but your full name is unlikely to be less than 1 char or more than 100.

Or in e-commerce where we have complex pricing formulas (items like showers that need to be custom built for the customer) need to be configured and priced with some very complex formulas, often market dependent, and types just sing and avoid you multiplying a generic number (which will need to be a positive € schema) with a swiss VAT rate.

davidmurdoch

Your can do that now in Typescript. But it will take several minutes to resolve your types. I've done it and it's a horrible dev experience, sadly.

raincole

robertlagrant

Thank you - I didn't know it had a name. But I'm not surprised it came from ML.

britch

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.

null

[deleted]

ryanpetrich

Should 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");

h1fra

so like assert(process.env.MY_ENV_VAR) but in a less readable oneliner?

t-writescode

Since JS doesn’t have if statements return values, null chaining is a great way to keep both const variables and have some level of decidability.

Null chaining is also a common pattern across most languages and is generally seen as readable

MobiusHorizons

I get why we prefer final in languages with a need for thread safety, but I have never understood why people prefer const in typescript. I have seen people bend over backwards to avoid a `let` even if it results in higher complexity code. It just doesn’t seem to solve a problem I’ve ever actually encountered in typescript code.

ameliaquining

There isn't a built-in assert function that behaves that way; you would need to either write it or import it.

jackblemming

That doesn’t assign it to the shorthand local variable.

zdragnar

It could return the given value if it doesn't throw, though, which would make using it with assignment trivial.

cypressious

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

robertlagrant

From the article:

> In Rust, however, you're forced to reason about the "seriousness" of calling .unwrap() as it could terminate your program. In TS you're not faced with the same consequences.

paulddraper

Yes that was a mistake.

unwrap() is the error.

unwrap_or() is the fallback.

flufluflufluffy

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.

superjose

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!

SkiFire13

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

ameliaquining

Semantically the two are kind of opposite; the similarity is that they're the lowest-syntax way in their respective languages to ignore the possibility of a missing value, and so get overused in situations where that possibility should not be ignored, leading to bugs.

GMoromisato

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.

raincole

JavaScript isn't even statically typed.

> Why not cast to a non-undefined type as soon as we're sure (and throw if it is not)

This is exactly what the OP author suggests.

ameliaquining

If your type definitions are airtight then this problem doesn't come up, but sometimes, for whatever reason which may not be entirely within your control, they aren't. Narrowing and failing early is precisely what the article advises doing.

vadansky

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.

renewiltord

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.

noman-land

This is a fine line. If you get a white screen of death you know something is wrong. If the first name is missing it may mean other things are missing and the app is in a bad state. That means the user could lose any work they try to do, which is a cardinal sin for an app to commit.

Context matters a lot. If it's Spotify and my music won't play is a lot different than I filled a form to send my rent check and it silently failed.

hahn-kev

Totally agree, I think this is a good place for debug asserts which only throw during development, but fallback in prod builds.

pverheggen

Well, what would be better is “Hi, you have…”, and that would require a conditional, not coalescing.

polishdude20

Exactly, something like a name missing shouldn't cause the app to completely error out for the user.

slooonz

Yes it should, because hopefully errors are logged and reported and can be acted upon. Missing name doesn’t.

pitched

If the error isn’t repairable by the user, blocking them from using the app entirely is mean. If the error screen has a message telling the user where to go to set their name, that’s fine but annoying. If the error screen tells the user they can’t use the app until someone checks a dashboard and sees a large enough increase in errors to investigate, that’s a bigger problem.

noman-land

Why not both?

jackblemming

This reads like a dogmatic view of someone who hasn’t worked on a project that’s a million plus lines of code where something is always going wrong, and crashing the entire program when that’s the case is simply unacceptable.

btdmaster

See also "Parse, don't validate (2019)" [0]

[0] https://news.ycombinator.com/item?id=41031585