`null` vs. `undefined` in TypeScript land

BASARAT
2 min readMar 11, 2016

--

Having `null` and `undefined` as two distinct things in JavaScript is honestly painful. If you are a JavaScript dev (before you learnt pretty much any other language) you might like it. I don’t. Flow lang chooses to denote both with a single `?` type annotation. For TypeScript options are being discussed.

But the difference is not something that has ever caused me distress or pain as far as I can remember. Here are some tips that might be the cause.

Don’t use null

I almost never use null. Unless the ecosystem dictates it e.g. node style callbacks expect the error argment to be set to null in case of no error. Even then I (and pretty much everyone else) does a truthy check on null and not an explicit one. So:

Does this function care if err is null or undefined. Nope.

In fact the TypeScript compiler source doesn’t use `null` only `undefined`.

And even Crockford doesn’t use null anymore and now considers it a bad part of JavaScript.

Don’t compare to null

If you suspect `null`|`undefined` just go with a truthy check. If a falsy value is a valid value (e.g. ‘’, false, 0) then filter out both null and undefined with `== undefined` as it works with `null` and `undefined` but not for other falsy values.

For default values to functions let the TypeScript compiler do the `undefined` check for you.

Don’t initialize optional sub properties

Just don’t set it. Your type annotation should have it as optional anyways. Don’t set it to `null` or `undefined`. Just have it as absent:

Of course your type annotation better have it marked as optional for this to work.

Have another property to denote validity instead of undefined

I use optional returns. But generally only when the function is called within the same file. A quick contrived example of a bad function:

As soon as the function is exported or too complex its trivial to come up with an inline type declaration (TypeScript is awesome that way and not another painful typed language).

I’ve tried to use a maybe but it just seems like an overkill considering all the other awful things that developers can write.

As always this is just a guideline. Would love to hear your opinions 🌹

--

--

Responses (4)