isNotNullable - Check if a variable is not nullable in Typescript

Sandro Maglione

Sandro Maglione

Web development

In every Typescript codebase is often necessary to check if a variable is null or undefined.

There seems to be many ways to achieve this goal. You can check out this question on StackOverflow for more details on the matter. You can also read this discussion on StackOverflow on how to check if a variable is undefined (hint: use typeof!).

Regardless of the means, we want Typescript to ensure us that a generic type T | null | undefined is not nullable, meaning that it is neither null nor undefined.

We can use the isNotNullable function showed below to achieve this 🎉👇.

The isNotNullable function uses a type-guard to ensure that the returned type is T when the function returns true.

const isNotNullable = <T>(element: T | null | undefined): element is T =>
  typeof element !== "undefined" && element !== null;

Using this function, we can ensure that a variable is actually defined. Look at the example in the code below:

const isNotNullable = <T>(element: T | null | undefined): element is T =>
  typeof element !== "undefined" && element !== null;
 
const func = (item: { name: string } | null | undefined) => {
  if (isNotNullable(item)) {
    // Here `item` is of type `{ name: string }`, guaranteed!
    return item.name;
  }
 
  return "Nullable!";
}
 
console.log(func({ name: 'Typescript' })); // Typescript
console.log(func(null)); // Nullable!
console.log(func(undefined)); // Nullable!

Inside func Typescript can ensure that item has a name using the type-guard on isNotNullable. After the if statement instead, Typescript will narrow the type of item to either null or undefined. By doing so, we are not allowed to access name anymore.

Check out the example on this Typescript Playground.

Happy coding 💻!

👋・Interested in learning more, every week?

Every week I build a new open source project, with a new language or library, and teach you how I did it, what I learned, and how you can do the same. Join me and other 600+ readers.