-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
55 lines (53 loc) · 1.34 KB
/
index.ts
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
import Guard from "../../Guard";
import TValidate from "../TValidate";
/**
* Validates the shape of an object.
*
* @returns
* A `Guard` that checks if the given value matches the provided object shape.
*
* Accpets not-null objects, where all `keys`
* and `values` are accepted by the given shape `guards`.
* Similar in concept as TypeScript's `{[keys: string]: number}` type annotations.
*
* `guard.name: "{ [<keyType>]: <valueType> }"`
*
* @param shape
* The guards, which will validate the keys and values of the given object.
*
* @example
* ```ts
* const guard = TObjectShape({
* keys: TString,
* values: TNumber,
* });
*
* guard.isValid({
* avocado: 2,
* orange: 5,
* }); // true
*
* guard.isValid({
* avocado: "green",
* orange: 5,
* }); // false
*
* guard.name === "{ [string]: number }"; // true
* ```
*/
export default function TObjectOfShape<T>(shape: {
keys: Guard<string>;
values: Guard<T>;
}): Guard<Record<string, T>> {
const name = `{ [${shape.keys.name}]: ${shape.values.name} }`;
return TValidate<Record<string, T>>(name, (value) => {
{
if (typeof value !== "object" || value === null) return false;
for (const key in value) {
if (!shape.keys.isValid(key)) return false;
if (!shape.values.isValid(value[key])) return false;
}
return true;
}
});
}