Skip to main content
Practice Problems

Utility type nonnullable in TypeScript

What is NonNullable?

NonNullable<T> constructs a type by excluding null and undefined from T. It ensures a value is definitely present.


Basic Usage

typescript
type MaybeString = string | null | undefined; type DefiniteString = NonNullable<MaybeString>; // string type MaybeNumber = number | null; type DefiniteNumber = NonNullable<MaybeNumber>; // number type Complex = string | number | null | undefined | boolean; type Cleaned = NonNullable<Complex>; // string | number | boolean

How It Works Internally

typescript
// NonNullable is defined as: type NonNullable<T> = T & {}; // Or equivalently: type NonNullable<T> = T extends null | undefined ? never : T;

Practical Use Cases

Function Parameters

typescript
function processUser(user: NonNullable<User | null>): void { // user is guaranteed to be User, never null console.log(user.name); } // Equivalent to: function processUser(user: User): void { }

Array Filtering

typescript
const items: (string | null | undefined)[] = ["a", null, "b", undefined, "c"]; // Filter removes nulls, but TypeScript doesn't narrow automatically const filtered = items.filter(Boolean); // still (string | null | undefined)[] // ✅ Use NonNullable for proper typing const filtered = items.filter((item): item is NonNullable<typeof item> => item != null); // string[] // Or simpler: const filtered: string[] = items.filter((item): item is string => item != null);

Extracting from Optional Properties

typescript
interface User { id: string; name: string; email?: string; // string | undefined phone?: string | null; // string | null | undefined } type RequiredEmail = NonNullable<User["email"]>; // string type RequiredPhone = NonNullable<User["phone"]>; // string

Generic Constraints

typescript
function getValue<T>(value: T): NonNullable<T> { if (value == null) { throw new Error("Value cannot be null or undefined"); } return value as NonNullable<T>; } const result = getValue<string | null>("hello"); // result: string (not string | null)

With Other Utility Types

typescript
// Make all properties required AND non-nullable type Strict<T> = { [K in keyof T]-?: NonNullable<T[K]>; }; interface Config { host?: string | null; port?: number; debug?: boolean; } type StrictConfig = Strict<Config>; // { host: string; port: number; debug: boolean }

Important:

NonNullable<T> is essential for type-safe null handling. Use it to strip null/undefined from types, especially when working with optional properties, API responses, or filtering arrays. It pairs well with strict null checks (strictNullChecks: true).

Short Answer

Interview ready
Premium

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

Finished reading?
Practice Problems