NonEmptyArray
A type which indicates that an array is not empty.
type NonEmptyArray<T> = [T, ...T[]];
- You can use this to create a function like isNonEmptyArray that checks if an array has at least one element.
Example
function getFirstElement<T>(arr: T[]): T {
return arr[0];
}
const items: number[] = [];
// Runtime error
getFirstElement([]).toString();
// Type error
const fixItems: NonEmptyArray<number> = [];