DEV Community

Discussion on: Optional booleans?

Collapse
 
daniel13rady profile image
Daniel Brady • Edited

Optional booleans in APIs make sense to me in the same way that optionals in general make sense: they aren't optional to the API implementation, they're optional to the API consumer.

It's important to remember an optional boolean is not a boolean, it is a union type of boolean and whatever the type is for "value absence".

For many languages, this is tricky to work with, but Typescript and JavaScript make it easy.

A lot of people will rely on the simplicity of type coercion for implementing presence checks: if the value is "falsey", it's considered "absent."

function foo(x) {
  if (x) {
    alert("x is present");
  } else {
    alert("x is absent");
  }
}

But this of course breaks when the value is false exactly!

Instead, we should remember that in JS variables don't have types, only values do, and so doing a "presence check" on something that is supposed to be a boolean is as simple as asking typeof x == "boolean"!

function foo(x) {
  if (typeof x == "boolean") {
    alert("x is present");
  } else {
    alert("x is absent or not a boolean");
  }
}

In JS, if no value was provided, the type will be the string "undefined", and if a value is provided but isn't true or false the type will be something else.

This is amazing because it avoids the bugs that can happen when you try to determine presence based on the value itself.

Collapse
 
lexlohr profile image
Alex Lohr

Consider this more modern TS example:

const whatever = ({ darkMode = false, ...rest }) => null

It is not three different values, but a boolean value with a default so it can be optional.

If this was a component, every user would be forced to declare the darkMode property like it or not if it was not optional, which to me makes no sense if you can have a default.