Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Utility Types

TypeScript NonNullable<T> utility type

Reference for TypeScript NonNullable<T>: remove null and undefined from a type, how it works as an intersection, and how to use it in filters and guards.

NonNullable<T> removes null and undefined from T. Given string | null | undefined you get string. It is most useful when you have already checked a value (or filtered an array) and want to give the cleaned result an accurate type.

The compiler narrows variables automatically after an if (x != null) check, but it cannot always do the same for arrays or generic helpers. There, NonNullable<T> states what the code has just guaranteed.

TypeScript
type Maybe = string | null | undefined;
type Definite = NonNullable<Maybe>;
// string

Try it

TypeScript Filtering out missing values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Generic helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
type NonNullable<T> = T & {};
Name Description
T Any type. null and undefined are removed; everything else is kept.

Result: T without null and undefined. NonNullable<null | undefined> is never.

Edge cases: intersecting with {} removes null and undefined but leaves unknown as {} (so NonNullable<unknown> is {}). Before TypeScript 4.8 the definition was the conditional T extends null | undefined ? never : T, which behaved the same for most unions.

Usage notes

  • Type-level only. It does not check anything at runtime; use an if, ?? or a guard function to remove missing values for real.
  • Under strictNullChecks. The type is meaningful only with strict (or strictNullChecks) on. Without it, null and undefined are in every type already.
  • Narrowing on its own. After if (x != null) the compiler narrows x itself. Reach for NonNullable when the value is inside an array, a generic, or a property type you want to declare.
  • Filter with a type predicate. Array.prototype.filter does not narrow by itself; a function returning value is NonNullable<T> does, as shown above. Newer compilers can also infer such predicates from simple arrow functions.
  • Does not touch properties. NonNullable<{ a: string | null }> is unchanged; the null is inside a property. Use a mapped type with NonNullable on each property for that.
  • Added in TypeScript 2.8; the intersection form in 4.8.