-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-min-length.assert.ts
More file actions
39 lines (37 loc) · 1.2 KB
/
array-min-length.assert.ts
File metadata and controls
39 lines (37 loc) · 1.2 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
36
37
38
39
import { assertNonNullable } from "../non-nullable/non-nullable.assert.js";
import { AssertionError } from "../../assertion-error.js";
import { desc, repr } from "../../describe/describe.js";
/**
* Assert that an array has at least the expected minimum length, with type narrowing.
* The type narrowing indicates:
* - A non-empty array for 1
* - At least N elements up to 5
* - At least 5 elements for >5
*/
export function assertArrayMinLength<T, const N extends number>(
value: readonly T[] | undefined | null,
minLength: N,
message?: string,
): asserts value is N extends 0
? readonly T[]
: N extends 1
? readonly [T, ...T[]]
: N extends 2
? readonly [T, T, ...T[]]
: N extends 3
? readonly [T, T, T, ...T[]]
: N extends 4
? readonly [T, T, T, T, ...T[]]
: N extends 5
? readonly [T, T, T, T, T, ...T[]]
: readonly [T, T, T, T, T, ...T[]] {
assertNonNullable(value, message);
if (value.length < minLength) {
throw new AssertionError(
message ??
`Expected ${desc(value)} to have at least ${repr(minLength)} elements, but it had ${repr(value.length)}.`,
value,
{ minLength },
);
}
}