Abandon `null` in favor of `undefined`
See original GitHub issueFeature Request
Relevant Package
- @angular/forms
- Possibly any other package where null is used over undefined
Description
At the moment of writing this (June 2021), in the Angular code base, there seems to be no clear guideline for when to use null
and when to use undefined
. A brief search shows that (in the Angular code base starting from ./packages
) assignment to null
( = null
, notice the leading space to avoid matching === null
) occurs 1448 times, and assignment to undefined ( = undefined
) can be found 1905 times. While it is understandable to accept and properly handle passed null
values from the point of view of public api (because Angular is a framework after all and users should be able to use whatever value they like), it is not understandable (to me), why null
is used internally at all. This is problematic, because it makes it very easy for the null
value to bleed through Angular’s public api (which it shouldn’t!).
(Imho) Nowadays, the type null
just shouldn’t be used in modern TypeScript code any more. The reasons for that are simple:
- TypeScript offers handy shortcuts to “add” the
undefined
type to a type definition via?
character: e.g.myClassPropertyOrMethodParam?: number
. Usingnull
instead just feels awkward (e.g.myClassPropertyOrMethodParam: number | null
) and makes the code less readable. In that case you will end sooner or later addingundefined
, too (e.g.myClassPropertyOrMethodParam?: number | null
, some people even prefer to addundefined
explicitly in that case to “improve readability”myClassPropertyOrMethodParam: number | null | undefined
). undefined
is the natural default type of anything that has not been initialized.- last but not least, the classic:
typeof null === 'object' // sadly true
.
Consider Brendan Eich’s two-word suggestion: “Use undefined”
Example where null
bleeds through Angular API
There’s one module where it particularly bothers me, that Angular uses null
, because null
bleeds through. What I mean by “bleeding through” is, that the null
type is exposed via API that is consumed by Angular users:
The @angular/forms package assigns null
as the default value to a form control! See here and here!
Why is this a problem?
This is a serious problem (imho)! What Angular is doing here is very offensive! It is forcing its users (or say at least it’s tricking its users below senior level, which could well be >80%) to include the null
type in their own API / interfaces, because it’s just possible that a form control is in that state! This can make code more complicated than it has to be. It actively hinders people from trying to avoid null
inside their own code base. For example what I can see regularly in our code base are things like this:
export interface SomeType {
someProperty: number;
someOptionalProperty?: string | null
}
When I ask them why they’ve included null
in their type, what I usually hear as an explanation is “because otherwise it would not have been compatible with Angular Forms API”.
To be clear: while adding null
to someOptionalProperty
is no harm, it is just plain unnecessary here! While it looks like no big deal, it really is! Like cancer, adding null
to your types can spread easily to other places in your code base. A method that in the past was properly typed with optional parameters (param?: SomeType
) will soon be widened to accept null
as well (param?: SomeType | null
). This is, because in a lot of projects, developers just need to get work done, so it’s understandable why they’re saying “it’s easier than fixing the null
type in my interface right now” and “I’m in a hurry and need to call that method now!”.
Where null
can’t be avoided
You can’t always avoid having null
values. This is, because JSON doesn’t know the type undefined
, it only knows null
. However, in my eyes, this is not an excuse to carry the null
type around all over the code base. I’m not saying to not accept null
values coming in from JSON. All I’m saying is to stop using null
actively.
How does a code base not using null
at all look like?
When following a few coding guidelines, null
can always be implicitly treated as undefined
and thus there’s no need to add it to any types / interfaces at all.
Here are the guidelines that make it possible:
- avoid direct undefined type guards (e.g.
if (value === undefined) { ... }
. - Instead, use indirect type guards (aka truthiness checks) e.g.
if (value) { ... }
- Whenever 0 or empty strings are meaningful, use either
- an explicit helper method like Lodash’s
isNil
- or include the meaningful value in the comparison (e.g.
if (!value && value !== 0) { ... }
)
- an explicit helper method like Lodash’s
- Consider using a lint rule that disallows the usage of
null
Describe the solution you’d like to see in Angular
- all public api should continue to accept
null
(ideally only as part ofany
type) and handle it properly - all public api should stop returning
null
values - all public api that used to return
null
values should returnundefined
instead ofnull
Consequences for Angular
I know that this is a huge change and a breaking one as well. A rather long deprecation period would therefore be needed for user adoption.
Describe alternatives you’ve considered
As it is a matter of (admittedly very debatable) taste, there will surely exist a multitude of alternatives and other opinions. I would like to not open up discussion here on how null
is useful to somebody in some cases. Such a discussion can be found here … Instead, please just up/downvote this feature request if you agree/disagree. Thanks a lot!
Best Regards, Nic
Issue Analytics
- State:
- Created 2 years ago
- Reactions:47
- Comments:9 (3 by maintainers)
Top GitHub Comments
Funny; I’d be using only
null
instead of onlyundefined
if I had to strictly choose.Firstly, while I agree that there should be a convention, I don’t think all instances of either can be replaced with one of those. As you said,
which, to me, means that
undefined
would be the value of something that I’ve never touched; but if I explicitly define something, then tha would be initialize withnull
. It wouldn’t make sense to me to “initialize something with the value that is used when something is not initialized”.For example, the way I see it,
Map#get
should returnundefined
when you try to access a key that hasn’t been defined (yet). It doesn’t make sense to imagine a code that firstly sets all possible keys to the value ofnull
(there can be infinitely many if you ignore practical hardware constraints). However, when there’s a finite, pre-defined set of possible keys,null
can be the “default” value which means “nothing”; e.g.Element#onclick
isnull
by default because nothing will happen when an element is clicked, but it’s clear that it’s possible for something to happen (compare with asking forElement#onsing
, which returnsundefined
and points to a fact that you might’ve made some mistake, since it doesn’t make sense to listen to a nonsense event).For example, I agree that
async
pipe should returnundefined
before it sees a first subscription, precisely because I expect to usenull
myself for something meaningful.undefined
could produce a loading indicator in the view, whilenull
could tell me that some value is explicitly “nothing”.Secondly, you suggest some strategies which I’ve seen people avoid with time, including myself.
This is a footgun whenever a falsy value should not be treated as
null/undefined
. For example,0
can have a different meaning thanundefined
(e.g.delete (count?: number)
might delete all elements when called asdelete()
, but obviously delete no elements when called asdelete(0)
).To avoid thinking about
null
andundefined
(since you don’t care in a lot of cases), you can useif (x != null)
.if (x !== undefined)
if (x)
if (x != null)
It’s also easier to understand the intent behind
x != null
over!x
.!
should be used only with booleans, since that’s the only place where its meaning is clear.I’m quite confused as your list then jumps to this example"
without even mentioning a simple
value != null
. Is the== null
something you’ve been purposely avoiding? If so, can you explain why?In all my professional career I never had the need to distinguish between something “initialized with null” and something that has not been initialized. For me, this is semantically the same thing. Even more so, because when you receive
null
from outside your application, you really never can be sure about the intended semantic there: did the developers responsible for managing that data (technically) thought ofnull
to mean “initialized explicitly and intentionally as null”, or is it justnull
because it’s theundefined
of the sql database world?Regardless, at runtime, it just doesn’t matter if something “is null” or “is undefined”. It’s both semantically the same thing: i.e. “nothing”. For example, you have been mentioning
Element#onclick
vs.Element#onsing
– for me the difference is irrelevant: if there’s nothing there,undefined
is just the right value; while the DOM specification decided to usenull
for a missingonclick
it better had chosenundefined
instead. Because in practice it just doesn’t matter if there COULD be aonclick
. If it’s not there it’s just not there … only if you really need the assurance at runtime that you really didn’t accidentally add a typo in youronclick
(checking withnull
, compared toonsing
returningundefined
) makes your argument a little bit valid, but that’s a matter of taste, for my part, I don’t need that because it’s a very weak argument and the benefit is almost zero to me, if not negative, because it adds unnecessary extra complexity to my code.Concerning your “async” example, I would rather recommend to use an explicit value for indication of “LOADING” state, rather than overloading “undefined” with that semantic.
This is exactly how Map#get works! But rather than needlessly “initializing” values with
null
I suggest you use Map#has instead to see if a value has been defined or not.That’s exactly why I’ve added the third rule:
Coming to your last argument:
Yes, I’ve been actively avoiding loose equality comparison with
null
, because it requires you to use, well …null
which (for me) is the general idea:null
is so utterly useless to me, that I don’t want to read it in my code at all, if not required for compatibility reasons (hopefully limited to a very few places where interoperability with data coming from outside / third party libs is required). Adding to that, I think it’s useful, in general, to avoid loose equality comparisons and use strict equality comparisons instead, because for most people, implicit type conversion is a black box resulting in their code becoming kind of a random surprise egg – working in most happy cases and sometimes just not working quite as expected. It’s far easier to learn the rule for “truthiness/falsiness” (i.e. conversion from anything -> boolean) than for conversion from anything -> anthing.