Non-empty array type
Encode "at least one element" in the type so head, max and similar functions never see an empty array.
- TypeScript
- GreenSnippets
- MIT
- Executed with Node.js 22 (type stripping)
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
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.
Related snippets
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- JavaScript Tested
Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.
- PHP Tested
Group an array of records by a key
Turn a flat list of associative arrays into groups keyed by a field or callback.
- TypeScript Tested
Generic groupBy with key inference
Group an array into a Record by a property or function while keeping the item type.

