isNonEmptyArray function
Checks whether an array has an item, and narrows it so that its first item is defined.
ts
import { isNonEmptyArray } from 'utils';Signature
ts
export function isNonEmptyArray<T>(items: readonly T[]): items is NonEmptyArray<T>Parameters
| Name | Description |
|---|---|
T | The type of the items. |
items | The array to check. |
Returns
true when the array has an item.
Example
ts
if (isNonEmptyArray(samples)) {
const [first] = samples; // a sample, not `undefined`
}Tests
Line coverage: 100 %.
- ✅ checks the length
- ✅ types the first item as defined
Source
src/guard/is-non-empty-array.ts (on GitHub)
Uses
NonEmptyArray: An array with at least one item, so that its first item is neverundefined.
Files it needs
src/guard/is-non-empty-array.ts imports, directly or not:
Source code
ts
import type { NonEmptyArray } from '../types';
/**
* Checks whether an array has an item, and narrows it so that its first item is defined.
*
* @template T - The type of the items.
* @param items - The array to check.
* @returns `true` when the array has an item.
* @example
* if (isNonEmptyArray(samples)) {
* const [first] = samples; // a sample, not `undefined`
* }
*/
export function isNonEmptyArray<T>(items: readonly T[]): items is NonEmptyArray<T> {
return items.length > 0;
}Test file
ts
import type { NonEmptyArray } from '../types';
import { isNonEmptyArray } from './is-non-empty-array';
describe(isNonEmptyArray, () => {
it('checks the length', () => {
expect(isNonEmptyArray([0])).toBe(true);
expect(isNonEmptyArray([])).toBe(false);
});
it('types the first item as defined', () => {
expectTypeOf(isNonEmptyArray<number>).guards.toEqualTypeOf<NonEmptyArray<number>>();
});
});Keywords: is, non, empty, array, guards, function