โ€ข

tech

isNotNullable - Check if a variable is not nullable in Typescript

Function used to check if a variable is not nullable and narrow its type using Typescript.


Sandro Maglione

Sandro Maglione

Software 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?

Timeless coding principles, practices, and tools that make a difference, regardless of your language or framework, delivered in your inbox every week.