Course contentsShow
← TypeScript
Lesson 1345 of 1,79631. Type-Driven DesignFree lesson

Empty Array Edge Cases

Using NonEmptyArray branded types when operations require at least one element to be meaningful.

Empty Array Edge Cases

You'll learn how to use branded NonEmptyArray types to prevent runtime errors in operations that require at least one element to exist.

The Problem with Empty Arrays

Many array operations assume at least one element exists. Consider finding the maximum value, getting the first element, or calculating an average. When you pass an empty array to these functions, they either return undefined, throw errors, or produce nonsensical results like NaN.

TypeScript's standard Array<T> type doesn't distinguish between arrays that might be empty and arrays that definitely have elements. This means the type system can't prevent you from calling array[0] on what might be an empty array—you'll get undefined at runtime, even though TypeScript thinks you have a T.

The NonEmptyArray Pattern

A branded type (or phantom type) lets you mark certain arrays as guaranteed non-empty:

type NonEmptyArray<T> = [T, ...T[]] & { __brand: 'NonEmptyArray' };

This says: "A NonEmptyArray is a tuple with at least one element of type T, followed by any number of additional T elements."

The __brand property is a phantom field—it exists only at compile-time to prevent accidentally treating a regular array as non-empty.

Building Safe Utilities

function max(numbers: NonEmptyArray<number>): number {
  // Safe! We know numbers[0] exists
  let result = numbers[0];
  for (let i = 1; i < numbers.length; i++) {
    if (numbers[i] > result) result = numbers[i];
  }
  return result;
}

function createNonEmpty<T>(first: T, ...rest: T[]): NonEmptyArray<T> {
  return [first, ...rest] as NonEmptyArray<T>;
}

const scores = createNonEmpty(85, 92, 78);
const highest = max(scores); // ✓ number, never undefined

Notice max returns number, not number | undefined, because we've encoded the non-empty constraint directly in the type.

Think of It Like a Contract

A NonEmptyArray is like a vending machine that guarantees at least one item. Regular arrays are like vending machines that might be empty. If your function needs to dispense something, require the non-empty version—don't accept machines that could be out of stock.

Key Takeaway: Use NonEmptyArray branded types when operations like first(), max(), or average() would be meaningless or unsafe on empty arrays, shifting runtime checks into compile-time guarantees.