Nullable<string> => Option => Empty string approach

Hello Forum!

I’m new to Rescript an am trying to port some JavaScript over to it.

I’ve got a Regular expression and am extracting strings from a match’s captures. This involves converting a nullable to an option and then performing the switch defined below:

let getString = (c: Js.Nullable.t<string>) => switch Js.Nullable.toOption(c) {
    | Some(m) => m
    | None => ""
  }

It works but is likely not idiomatic Rescript. I’m looking for for basic feedback on how this would be improved.

Thanks!

As a side note: I think there ought to be a section in the Forum for Beginner questions.

This actually looks like pretty standard ReScript. There isn’t anything especially wrong or not idiomatic about it.

But for the sake of learning/discussion, another alternative is to use the Belt.Option module instead of switch statements:

let getString = c => c->Js.Nullable.toOption->Belt.Option.getWithDefault("")

The switch version will compile to slightly lighter JS. The Belt.Option.getWithDefault version is nicer for when you’re chaining a lot of functions. Either one will accomplish the same thing.

3 Likes

We don’t intend to have a newcomer section because the general section should be welcoming enough of all questions, as a newcomer question isn’t always correlated to its shallowness, and especially in up-and-coming programming languages, it’s the seemingly “advanced” questions that need their fanciness dialed down: Beginner Category? - #2 by chenglou

Anyway, yes! You’ve demonstrated one necessary conversion + one switch. This is as close as you get to the theoretical minimal amount of conversion code. I think it does speak volume to our approach that you end up with the right solution just like that. Again, no fancy tricks. It’s just a null value.

Some tips:

  • If you know it can only be null and never undefined, try Js.Null.toOption, which explicitly doesn’t handle undefined. That’d convey a tighter intent.
  • If it can only be undefined, then you can just switch on it without the converter, since we map None to undefined.
  • getWithDefault is nice but as much as possible, prefer the barebone switch.
3 Likes

Thanks for the reply. In this particular case the value is being returned from Js.Re.captures as so is an array of nullables, so I think I don’t have the choice. But that’s good to know.

Interesting, I’ll give the Belt lib a read through.