Replace uses of `null` with `undefined`
See original GitHub issueI call it my billion-dollar mistake. It was the invention of the null reference in 1965.
JavaScript unfortunately has two billion-dollar mistakes: null
and undefined
.
While we can’t remove them from the language, we can reduce our usage down to a single type. I’d like to propose that we replace all uses of null
with undefined
.
The reason I suggest undefined
is due to its natural existence through JavaScript and TypeScript. For example, check out this TypeScript function with an optional argument:
function useOptionalArg(optionalArg?: string) {
console.log(optionalArg)
}
The use of the ?
operator makes optionalArg
have a type of string | undefined
.
Additionally, using only undefined
allows us to avoid awkward type situations like this one:
The type of provider
on line 22 is ethers.providers.Web3Provider | null | undefined
. This is due to the way provider
is defined on Web3Context
:
There’s no reason for it to also be typed as null
when it’s already potentially undefined
due to it being optional.
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (5 by maintainers)
Top GitHub Comments
That’s interesting that you lay that case out @etr2460 because I used to hold the same view. I was pushing for essentially the same idea at my last startup I worked for and ran into a few issues:
null
is enforceable, see:unicorn/no-null
by @sindresorhus)We ended up moving everything to
undefined
and it basically didn’t matter in the slightest so I came to see it as being an idea that seemed interesting and useful, but in practicality it’s just not. imo there are better ways to handle the situation that makes it more obvious to the consumer than “know the distinction betweennull
andundefined
”.I guess as an example, if
getENSAddress
was exported from some library and the user didn’t know about the distinction, would its types suggest to the user how to use it? Not really, they’d assume it means there’s no address and come asking how they could distinguish between loading and just not having one yet. If it was something like{ isLoading: true; address: undefined } | { isLoading: false; address?: string }
, it’d provide a lot more context out of the box (at least for TypeScript users).closing because of massive structure change