Non-Empty Tuples Guarantee A First Element
Type rest tuples as [T, ...T[]] so first() returns T instead of T | undefined and zero-length arrays fail compilation instead of crashing later.
Code
type NonEmptyArray<T> = [T, ...T[]];
// A non-empty tuple guarantees a first element, so first() returns T
// instead of T | undefined — no guard needed at the call site.
function first<T>(items: NonEmptyArray<T>): T {
return items[0];
}
// A rest parameter typed [T, ...T[]] rejects calls with zero values
// at compile time, before the log line can ever come out empty.
function logReadings(label: string, ...values: NonEmptyArray<number>): string {
return `${label}: ${values.join(' ')}`;
}
const readings: NonEmptyArray<number> = [21.5, 22.1, 20.9];
console.log(first(readings));
const queue: NonEmptyArray<string> = ['auth', 'sync', 'report'];
console.log(first(queue));
console.log(logReadings('batch', 1, 2, 3));
console.log(logReadings('single', 9));
// Both of these fail compilation, not at runtime:
// const empty: NonEmptyArray<number> = [];
// logReadings('no values');Output
Captured from a sandboxed run of this snippet in the build pipeline.
21.5
auth
batch: 1 2 3
single: 9The one-type change that removes a runtime guard
type NonEmptyArray<T> = [T, ...T[]] puts “at least one element” into the type: the head is mandatory, the rest are optional repeats. That is why first<T>(items: NonEmptyArray<T>): T can return items[0] with return type T instead of T | undefined — the compiler, not a call-site guard, now owns the empty case. Assigning const empty: NonEmptyArray<number> = [] (commented out in the file) fails compilation rather than crashing at runtime.
What the demo prints
21.5
auth
batch: 1 2 3
single: 9
first(readings) pulls the head 21.5 from the number tuple and first(queue) pulls 'auth' from the string tuple. The rest-parameter form ...values: NonEmptyArray<number> in logReadings rejects a zero-value call at compile time — logReadings('no values') is the second commented-out failure — while 'batch', 1, 2, 3 and the single-value 'single', 9 both compile and join their values after the label.
The line that benefits directly
function first<T>(items: NonEmptyArray<T>): T {
return items[0];
}
With T[] instead, the same return would need a T | undefined signature or a runtime throw; the tuple’s mandatory head is the entire guarantee.
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `first`, `logReadings` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.