loading...

TypeScript - undefined vs null

andreasbergqvist profile image Andreas Bergqvist ・2 min read

So the undefined vs null discussion might seem ancient in the JavaScript world. But for me, the question arises again the more I move over to TypeScript.

There seems to be 3 different "camps" when I try to read posts regarding this...

TL;DR

I will try to NOT use null and trying to only use undefined.

I read enough comments from people that has done this and seems happy with it to give it a try.

Pros:

  • "Easier" syntax let variable?:Type; vs let variable:Type = null or let variable?:Type = null;
  • Most other languages seems to have just one type for this!
  • Code does not need to handle both.

Cons

  • Longer to write
  • The difference between an actually undefined variable vs a variable set to null is lost.
  • JSON can only handle null and not undefined.

Camp 1 - use both

So, an alternative could absolutely be to use both. And this is how I have donw previously.
But, as mentioned in the TL;DR, most other languages seems to manage without both, and as a programmer, you might need to handle both undefined and null variables, which can make the code more complex.

The pros are, as mentioned, that there now is a difference between an actually undefined variable and one set to null.

const [value, setValue] = useState<number| null>(); 
let value?:number | null;
// value = number | null | undefined

Camp 2 - use null

null is a word more used in other languages AND is shorter to write!
Is also works nicely with JSON APIs.

The extra code needed is well worth to be able to differentiate.

const [value, setValue] = useState<number| null>(null); 
let value:number | null = null;
// value = number | null

Camp 3 - use undefined

There should be no need of two typed and undefined is the default one when not setting a value.

Array functions is JavaScript return undefined.

const [value, setValue] = useState<number>(); 
function (value?:number) {}
// value = number | undefined

Discussion

markdown guide
 

You should check out the discussion @sindresorhus started on Twitter about this. Very relevant to your post.