-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-not-empty.assert.ts
More file actions
35 lines (30 loc) · 1.04 KB
/
Copy patharray-not-empty.assert.ts
File metadata and controls
35 lines (30 loc) · 1.04 KB
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
29
30
31
32
33
34
35
import { nonEmptyArray } from "./array-not-empty.match.js";
import { AssertionError } from "../../assertion-error.js";
import { desc } from "../../describe/describe.js";
import type { NonEmptyArray } from "./array-not-empty.type.js";
export function assertArrayNotEmpty<TArray extends unknown[]>(
value: TArray,
message?: string,
): asserts value is TArray & NonEmptyArray<TArray[number]>;
export function assertArrayNotEmpty(
value: unknown,
message?: string,
): asserts value is NonEmptyArray<unknown>;
/**
* Assert that an array has at least one element, with type-narrowing.
*/
export function assertArrayNotEmpty(value: unknown, message?: string): void {
if (!nonEmptyArray().matches(value)) {
throw new AssertionError(
message ?? buildArrayNotEmptyMessage(value),
value,
["..."],
);
}
}
function buildArrayNotEmptyMessage(value: unknown): string {
if (!Array.isArray(value)) {
return `Expected ${desc(value)} to be a non-empty array.`;
}
return `Expected array not to be empty, but it was empty.`;
}