/
shape.ts
47 lines (42 loc) · 1.16 KB
/
shape.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
import { createSchema } from '../createSchema';
import { commonCriteria, shapeCriteria } from '../criteria';
import { createObject, invariant, isObject } from '../helpers';
import {
Blueprint,
CommonCriterias,
Criteria,
InferNullable,
Schema,
ShapeCriterias,
} from '../types';
export interface ShapeSchema<T>
extends Schema<T, Partial<T>>,
ShapeCriterias<ShapeSchema<T>>,
CommonCriterias<ShapeSchema<T>> {
never: () => ShapeSchema<never>;
notNullable: () => ShapeSchema<NonNullable<T>>;
nullable: () => ShapeSchema<T | null>;
/** @internal */
of: <S extends object>(schema: Blueprint<S>) => ShapeSchema<InferNullable<T, S>>;
}
function validateType(): Criteria<unknown> | void {
return {
skipIfNull: true,
validate(value, path) {
if (value === undefined) {
// Will be built from its items
return {};
}
invariant(isObject(value), 'Must be a shaped object.', path);
return value;
},
};
}
export function shape<T extends object>(blueprint: Blueprint<T>): ShapeSchema<T> {
return createSchema<ShapeSchema<T>>({
cast: createObject,
criteria: { ...commonCriteria, ...shapeCriteria },
type: 'shape',
validateType,
}).of(blueprint);
}