Skip to content
GreenSnippets

Non-empty array type

Encode "at least one element" in the type so head, max and similar functions never see an empty array.

TypeScript
type NonEmptyArray<T> = [T, ...T[]];

function isNonEmpty<T>(array: readonly T[]): array is NonEmptyArray<T> {
  return array.length > 0;
}

function maxOf(numbers: NonEmptyArray<number>): number {
  return Math.max(...numbers);
}

function first<T>(array: NonEmptyArray<T>): T {
  return array[0];
}

Example / expected output

Output
const scores = getScores(); // number[]
if (isNonEmpty(scores)) console.log(maxOf(scores));

How it works

Instead of checking for empty arrays at runtime everywhere, make the invalid state unrepresentable. The tuple type [T, ...T[]] guarantees an element at index 0. A small guard converts ordinary arrays when you need to.