Hacker News new | ask | show | jobs
by j1elo 1468 days ago
TypeScript is nice because its null type is explicit. So if a type claims to be bool, it is really bool (either true or false, nothing else).

For a nullable variable of type T (including boolean), the type must be explicit about it:

    let choice: T | null;
Another nice alternative is an Option type, like Rust has. I think it would be something like Option<bool>.

But those (a null, or a None, respectively) would be only choices if internally, at the code level, the Unset case must be handled as some kind of extraordinary scenario. If it was possible for users to make a conscious decision to leave it unset, i.e. if Unset is part of the valid choices offered by the user-facing API, then I'd encode it as a proper possible state, in an enum.

1 comments

And it's terrible because there's both `null` and `undefined` which have largely the same meaning but aren't equal. Depending on what you're interacting with, you may need to use one over the other or coerce. Especially common with developers from other languages who don't even know of the gotcha
I've never found a use for null where undefined wouldn't be simpler to use. Especially with the ?? Operator to set defaults along the way
This is a very curious and fun way to put it:

https://stackoverflow.com/a/57249968

In essence, `undefined` is non-existence. And `null` is existence with a non- (or "invalid", or "unknown") value.

Although using them like that depends on the needs of the application. If "invalid" or "unknown" was an expected user choice, I would still rather encode it as an enum better than a nullable boolean, as mentioned in my comment above.