TypeScript NonNullable Guide

October 26, 2023

TypeScript, with its static type checking, provides a way to catch certain types of errors during compile time. One of its powerful type manipulation tools is NonNullable<T>, which filters out null and undefined from a given type. In this guide, we'll dive into the NonNullable utility type and its practical uses.

Basic Understanding of NonNullable<T>

The NonNullable<T> utility type represents a type that doesn't allow null or undefined.

type NonNullable<T> = T extends null | undefined ? never : T;

When applied, this type will exclude null and undefined from the type T.

Example:

type MaybeString = string | null | undefined; type StringOnly = NonNullable<MaybeString>; // Result: string

Practical Usage Scenarios

Function Parameters

If you have a function that should not accept null or undefined values, NonNullable can be handy.

function printValue(value: NonNullable<string | null | undefined>) { console.log(value); } printValue("Hello"); // OK printValue(null); // Error printValue(undefined); // Error

Filtering Arrays

When working with arrays that might contain nullable values, you can use NonNullable in combination with a filter to remove them.

const items: (string | null | undefined)[] = ["apple", null, "banana", undefined, "cherry"]; const filteredItems: string[] = items.filter((item): item is NonNullable<typeof item> => item !== null && item !== undefined);

Working with Object Properties

For objects that might have optional properties, you can use NonNullable to ensure some properties always have a value.

interface User { id: number; name?: string | null; } function getUserName(user: User): NonNullable<User['name']> { if (!user.name) { throw new Error("User has no name!"); } return user.name; }

Gotchas and Limitations

While NonNullable is powerful, it's essential to remember its scope:

It Doesn't Alter Runtime Behavior

Like other TypeScript features, NonNullable only provides static type checking. It doesn't change the runtime behavior of JavaScript. Always ensure that you handle potential null or undefined values in your runtime code.

Requires Strict Null Checks

For NonNullable to be effective, you should enable the strictNullChecks compiler option in your tsconfig.json. This ensures that TypeScript enforces null and undefined checks.

{ "compilerOptions": { "strictNullChecks": true } }

Not Recursive on Nested Types

If you're working with deeply nested types, NonNullable won't recursively make all properties non-nullable. In such cases, you might need to apply NonNullable more deeply or create custom utility types.

Alternatives to NonNullable

If NonNullable doesn't quite fit your needs, TypeScript offers other utility types:

  • Required<T>: Makes all properties of T required.
  • Partial<T>: Makes all properties of T optional.
  • Readonly<T>: Makes all properties of T readonly.

Dive into TypeScript's utility types to find the right tools for your needs. They can significantly enhance type safety and developer productivity in your projects.

Ship faster, worry less with Basedash

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

Dashboards and charts

Effortlessly make charts and create a space for your team to work together towards shared goals and metrics.

User CRM

SQL composer with AI

Admin panel

Screenshot of a users table in a database. The interface is very data-dense with information.