TypeScript 7 reference · Utility Types

TypeScript NonNullable<Type> Utility Type

Remove null and undefined from a type, for values you've already checked or that can never be missing.

TypeScript 7 Since 2.8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

NonNullable<Type>

Parameters

ParameterDescription
Type The object type to transform.

Return value

Type without null and undefined.

Examples

Strip null and undefinedTry it yourself
type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>;
const n: Name = "Ana";
// @ts-expect-error: null is not allowed
const bad: Name = null;
console.log(n);

Output

Ana
A helper that guarantees a valueTry it yourself
function definitely<T>(value: T, message: string): NonNullable<T> {
  if (value == null) throw new Error(message);
  return value as NonNullable<T>;
}
const fromEnv: string | undefined = "8080";
const port = definitely(fromEnv, "PORT missing");
console.log(port.padStart(6, "."));

Output

..8080

Version history

VersionChange
TypeScript 2.8Added

Was this page helpful?