Repository navigation
Expand file tree
/
Copy patharray-includes.assert.ts
More file actions
57 lines (53 loc) · 1.64 KB
/
Copy patharray-includes.assert.ts
File metadata and controls
57 lines (53 loc) · 1.64 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { arrayIncluding } from "./array-includes.match.js";
import { AssertionError } from "../../assertion-error.js";
import { desc } from "../../describe/describe.js";
import type { ArrayIncluding } from "./array-includes.type.js";
export function assertArrayIncludes<
TArray extends unknown[],
const E extends TArray[number],
>(
value: TArray,
element: E,
message?: string,
): asserts value is TArray & ArrayIncluding<TArray[number]>;
export function assertArrayIncludes<const E>(
value: unknown,
element: E,
message?: string,
): asserts value is ArrayIncluding<E>;
/**
* Assert that an array includes a specific element, with type narrowing.
* Note that this is an identity match, so objects in an array only fulfill the
* assertion by being a reference to the same object, rather than equivalent in
* value to another object reference.
* Note that this uses the first element of the narrowed array type to indicate
* that the element is included, even though the element could be anywhere in
* the array.
* @example
* ```ts
* import { assertArrayIncludes } from "@kensio/smartass"
*
* const value: unknown = ["admin", "editor"];
*
* assertArrayIncludes(value, "admin");
*
* // value is now narrowed to an array including "admin"
* // ["admin", ...unknown[]]
*
* ```
*/
export function assertArrayIncludes(
value: unknown,
element: unknown,
message?: string,
): void {
const matcher = arrayIncluding(element);
if (!matcher.isMatch(value)) {
throw new AssertionError(
message ??
`Expected ${desc(value)} to include ${desc(element)}, but it did not.`,
value,
matcher.represent(),
);
}
}