diff --git a/packages/app/universal-ts-utils/src/array/isNonEmptyArray.spec.ts b/packages/app/universal-ts-utils/src/array/isNonEmptyArray.spec.ts new file mode 100644 index 00000000..e729d1cd --- /dev/null +++ b/packages/app/universal-ts-utils/src/array/isNonEmptyArray.spec.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { isNonEmptyArray } from './isNonEmptyArray' + +describe('arrayUtils', () => { + describe('isNonEmptyArray', () => { + it('returns false if array is empty ', () => { + expect(isNonEmptyArray([])).toBe(false) + }) + + it('returns true if array is not empty', () => { + expect(isNonEmptyArray(['hello', 'world'])).toBe(true) + }) + + it('type guard works', () => { + const array = [1, 2, 3] + if (!isNonEmptyArray(array)) throw new Error('Array should not be empty') + + // Ensure the type is inferred correctly at compile-time + type Assert = T extends Expected ? true : false + type Check = Assert + const isCorrectType: Check = true // If this line fails, type guard is not working + expect(isCorrectType).toBe(true) + }) + }) +}) diff --git a/packages/app/universal-ts-utils/src/array/isNonEmptyArray.ts b/packages/app/universal-ts-utils/src/array/isNonEmptyArray.ts new file mode 100644 index 00000000..49bebc7a --- /dev/null +++ b/packages/app/universal-ts-utils/src/array/isNonEmptyArray.ts @@ -0,0 +1,12 @@ +/** + * Checks if the given array is non-empty. + * + * This function is a type guard that not only checks whether the array has at least one element, + * but also refines the type of the array to be a tuple indicating that the first element exists. + * This is useful for preventing operations on empty arrays and for gaining type-level assurances. + * + * @template T - The type of elements within the array. + * @param {T[]} array - The array to be checked, which should be read-only. + * @returns {array is [T, ...T[]]} - Returns true if the array is non-empty, false otherwise. + */ +export const isNonEmptyArray = (array: T[]): array is [T, ...T[]] => array.length > 0