Skip to main content

What does NonNullable<T> do?

Definition

In the standard library it is implemented like this:

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

That is: if T is null or undefined, the result is never; otherwise T itself is returned.


Usage examples

javascript
type A = NonNullable<string | null | undefined>; // string type B = NonNullable<number | undefined>; // number type C = NonNullable<null | undefined>; // never type D = NonNullable<string | null>; // string

Practical use

  1. Safely accessing values after a check:
javascript
function getLength(value: string | null) { if (value) { let safe: NonNullable<typeof value> = value; // now definitely a string return safe.length; } return 0; }
  1. Typing API responses after filtering out null:
javascript
const users = [ "Tom", null, "Bob" ]; const valid = users.filter(Boolean) as NonNullable<typeof users[number]>[]; // valid: string[]
  1. Combined with other utility types:
javascript
type User = { name?: string | null }; type SafeUser = NonNullable<User["name"]>; // string

In short

UtilityPurpose
NonNullable<T>Removes null and undefined
Partial<T>Makes all fields optional
Required<T>Makes all fields required
Readonly<T>Makes all fields read-only
Extract<T, U>Keeps the intersection of types
Exclude<T, U>Removes the intersection of types

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.