Skip to content
Yeabsira on GitHub Yeabsira on Twitter

How to avoid null or undefined in TypeScript

I recently wanted to only accept anything but not null or undefined, and I want typescript to yell at me or throw an error if I pass null or undefined into the code at type level.

I know that I could specify that manually but in some cases, that is not the solution so there is a clever way of doing that, which is using Object or {}.

I could give example but its TypeScript-specific.

let’s say I wanted to accept anything but not null and undefined using generics.

type SomethingThatIsNotUndefinedOrNull<
	T extends string | number | boolean | string[] | number[] | boolean[]
> = {
	value: T
} // these are some of them, imagine if I want all types 😨
type SomeType = SomethingThatIsNotUndefinedOrNull<string> // It will work
type ItWillYellAtYou = SomethingThatIsNotUndefinedOrNull<null | undefined>

So what the solution, Here is the savior comes in ⇒ Object or {}

type SomethingThatIsNotUndefinedOrNull<T extends Object> = {
	value: T
} // Or {} instead of Object
type SomeType = SomethingThatIsNotUndefinedOrNull<string> // It will work
type ItWillYellAtYou = SomethingThatIsNotUndefinedOrNull<null | undefined>

But why does its work??

Here is the higher level of explanation:

Everything that has methods are object, simply everything in JavaScript is an object because every primitive type in JavaScript have an object Wrapper behind the scene, but null and undefined don’t have; that means they don’t have a method on them.

So, the reason why {} or Object can be used exchangeable even if

Object === {} // are not equal

is because an empty object ( {} ) is instance of Object or technical instance of built-in constructor function( Object).

{} instanceof Object // is True
// If you wanna try it, place {} in variable
// just like this
const EmptyObj = {}
EmptyObj instanceof Object

For a Deep Explanation about Object and {} also about object 😕 check out this: Link