isArrayOf function
Checks whether a value is an array whose every item passes a type guard.
ts
import { isArrayOf } from 'utils';Signature
ts
export function isArrayOf<T>(value: unknown, guard: (item: unknown) => item is T): value is T[]Parameters
| Name | Description |
|---|---|
T | Type of the items. |
value | The value to check. |
guard | The type guard applied to each item. |
Returns
true for an array of T (an empty array included).
Example
ts
isArrayOf([1, 2], isNumber); // true
isArrayOf([1, '2'], isNumber); // falseTests
Line coverage: 100 %.
- ✅ checks every item
Source
src/guard/is-array-of.ts (on GitHub)
Source code
ts
/**
* Checks whether a value is an array whose every item passes a type guard.
*
* @template T - Type of the items.
* @param value - The value to check.
* @param guard - The type guard applied to each item.
* @returns `true` for an array of `T` (an empty array included).
* @example
* isArrayOf([1, 2], isNumber); // true
* isArrayOf([1, '2'], isNumber); // false
*/
export function isArrayOf<T>(value: unknown, guard: (item: unknown) => item is T): value is T[] {
return Array.isArray(value) && value.every((item: unknown) => guard(item));
}Test file
ts
import { isArrayOf } from './is-array-of';
import { isNumber } from './is-number';
import { isString } from './is-string';
describe(isArrayOf, () => {
it('checks every item', () => {
expect(isArrayOf([1, 2], isNumber)).toBe(true);
expect(isArrayOf([], isNumber)).toBe(true);
expect(isArrayOf([1, '2'], isNumber)).toBe(false);
expect(isArrayOf('12', isString)).toBe(false);
});
});Keywords: is, array, of, guards, function