-
Notifications
You must be signed in to change notification settings - Fork 0
/
interface.ts
90 lines (87 loc) · 2.03 KB
/
interface.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { AnyHow } from "../anyhow/index.js";
import { ResultNew } from "../index.js";
export interface SchemaError extends AnyHow {}
export interface Schema<T> {
/**
* # Description
* Convert any value to a schema type.
* # Example
* ```ts
* const s = Schema.num();
* const v: Result<number> = s.parse(...);
* ```
*/
parse(v: unknown): ResultNew<T, SchemaError>;
/**
* # Description
* Test any value for schema type.
* # Warning
* Do not rely on `.check(v)` if you need to use `T` of schema.
* For example if your schema contains `Renum`, the `v` itself does not.
* If you need to use `v` better to use `.parse()`
* # Example
* ```ts
* const s = Schema.dict({
* field: Schema.num()
* });
* // valid usage
* if s.check(...) {
* // do some work
* }
* // dangerous usage
* const v = ...;
* if s.check(v) {
* someFn(v.field)
* }
* // Instead try to do this
* const v = ...;
* s.parse(v).inspect((v) => someFn(v.field))
* ```
*/
check(v: unknown): v is T;
}
/**
* # Description
* Function for transforming underlying `T`.
*
* Returns an `Api` where it's used from.
*
* Usefull when creating your own type.
* # Example
* ```ts
* interface SchemaNum<P = number> extends Schema<P> {
* transform: Transformer<number, SchemaNum<P>>
* }
* ```
*/
export interface Transformer<T, Api> {
(transformFn: (v: T) => ResultNew<T, SchemaError>): Api;
}
/**
* # Description
* Function for checking underlying `T`.
*
* Returns an `Api` where it's used from.
*
* Usefull when creating your own type.
* # Example
* ```ts
* interface SchemaNum<P = number> extends Schema<P> {
* is: Checker<number, SchemaNum<P>>
* }
* ```
*/
export interface Checker<T, Api> {
(checkFn: (v: T) => boolean): Api;
}
/**
* # Description
* Helper type for extracting schema type
*
* # Example
* ```ts
* const s = Schema.num().optional();
* type S = FromSchema<typeof s>; // Option<number>
* ```
*/
export type FromSchema<V> = V extends Schema<infer T> ? T : never;