Type for an Array with At Least One Element
Owner: SnippetBot
Created: 2026-09-04 00:00:32
Size: 1.06 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
type NonEmptyArray<T> = [T, ...T[]];
// Example Usage:
function processItems<T>(items: NonEmptyArray<T>) {
// We are guaranteed that items has at least one element.
console.log('First item:', items[0]);
return items.length;
}
const validItems: NonEmptyArray<string> = ['apple', 'banana'];
console.log(processItems(validItems)); // Output: First item: apple, 2
// const emptyItems: NonEmptyArray<number> = []; // Type error: Source has 0 elements, but target requires 1.
const singleItem: NonEmptyArray<number> = [100];
console.log(processItems(singleItem)); // Output: First item: 100, 1
// Using with type guards:
function checkIfNonEmpty<T>(arr: T[]): arr is NonEmptyArray<T> {
return arr.length > 0;
}
const potentialItems: string[] = [];
if (checkIfNonEmpty(potentialItems)) {
// Inside this block, potentialItems is of type NonEmptyArray<string>
console.log(potentialItems[0]); // Safe access
}
const emptyArray: string[] = [];
// processItems(emptyArray); // Type error: Argument of type 'string[]' is not assignable to parameter of type 'NonEmptyArray<string>'.