object-transforms

NonNullable<T>

Removes null and undefined from the type T. In TS 4.9+ it is implemented as `T & {}`, which drops nullish members without altering the rest.

type NonNullable<T> = T & {}

Usage patterns

Pattern Purpose
NonNullable<T> Strip null and undefined from a union
NonNullable<T[K]> Get a non-nullable value type from a property
arr.filter((x): x is NonNullable<T> => x != null) Runtime filter paired with the type
Exclude<T, null | undefined> Equivalent formulation using Exclude

Examples

type A = string | number | null | undefined;
type B = NonNullable<A>;

Result: string | number

function assert<T>(v: T): NonNullable<T> {
  if (v == null) throw new Error('nullish');
  return v as NonNullable<T>;
}

Common non-null assertion helper

type Name = NonNullable<User['nickname']>;

Pull the non-nullish variant of an optional property's value

type X = NonNullable<null>;

Result: never — no non-null members remain

Gotcha

Only removes null and undefined — it does not remove `void`, `0`, `''`, or `false`. Also it doesn't strip the optional `?` modifier from a property; use Required for that.

Related utility types

← All TS utility types · TypeScript vs JavaScript · any vs unknown vs never