-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnarrow.ts
211 lines (199 loc) · 5.17 KB
/
narrow.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/**
* Includes all values that can be returned by a `typeof` expression.
*/
export type Primitive =
| 'string'
| 'number'
| 'bigint'
| 'boolean'
| 'symbol'
| 'undefined'
| 'object'
| 'function'
export type NarrowerArr = Array<
Primitive | NarrowerObj | NarrowerArr | NarrowerSome
>
export interface NarrowerObj {
[k: string]: Primitive | NarrowerArr | NarrowerObj | NarrowerSome
}
/**
* This is the type that specifies a narrowed structure. The simplest form is a Primitive string,
* which will validate using a `typeof` comparison. Deeper structures can be defined using objects
* and arrays that will be validated recursively.
*
* @example
* // An array of mixed strings and numbers:
* ['string', 'number']
*
* // A deep object:
* {
* n: 'number',
* child: {
* word: 'string'
* },
* things: [
* ['number'],
* 'boolean'
* ],
* }
*/
export type Narrower = Primitive | NarrowerArr | NarrowerObj | NarrowerSome
export type UnPrimitive<N> = /*
*/ N extends 'string'
? string
: N extends 'number'
? number
: N extends 'bigint'
? bigint
: N extends 'boolean'
? boolean
: N extends 'symbol'
? symbol
: N extends 'undefined'
? undefined
: N extends 'object'
? object
: N extends 'function'
? Function
: unknown
/* eslint-disable @typescript-eslint/array-type */
/**
* This attempts to infer a narrowed type based on a Narrow schema, which results in nice types
* within conditional blocks. If inference is not possible, the type remains `unknown`.
*
* An empty array as a schema is a special case: TypeScript wants to assume the contained type is
* `never` (the array is empty, so the contents have no type) but this is not useful in practice, so
* the content type is also replaced with `unknown`.
*/
export type UnNarrow<N> = /*
*/ N extends Primitive
? UnPrimitive<N>
: N extends Array<never>
? Array<unknown>
: N extends Array<infer N2>
? N extends NarrowerSome
? UnNarrow<N2>
: Array<UnNarrow<N2>>
: N extends Record<keyof N, infer _N2>
? { [k in keyof N]: UnNarrow<N[k]> }
: unknown
/* eslint-enable @typescript-eslint/array-type */
/**
* This function validates any value with `typeof` checks. Arrays and objects are traversed
* according to the Narrower structure. The boolean return value is also a TypeScript type
* predicate.
*
* **Objects** -
* All keys of `n` are checked against `u` and their narrow is validated if the key exists.
* Keys that are missing from `u` are treated as having the value `undefined`. This means
* you can use `{ key: some('undefined', ...)}` to allow for missing/optional keys.
*
* **Arrays** -
* Including multiple types in a Narrower array allows for mixed types. Each item in `u` must
* satisfy at least one of the types.
*
* **Null** -
* `typeof null` is `'object'` but null cannot have any keys. Use `{}` to match an object
* that is not null.
*
* @example
* // An array of mixed strings and numbers:
* narrow(['string', 'number'], [1, 'two']) //=> true
* narrow(['string', 'number'], [{}]) //=> false
*
* // Null:
* narrow('object', null) //=> true
* narrow({}, null) //=> false
*
* // A deep object:
* narrow({
* n: 'number',
* child: {
* word: 'string'
* },
* things: [
* ['number'],
* 'boolean'
* ],
* }, {
* n: 3.14,
* child: {
* word: 'Yes'
* },
* things: [
* false,
* [1, 2, 3],
* true
* ]
* }) //=> true
*
* @param n The Narrower schema.
* @param u The value of unknown type to validate.
* @returns A type predicate that `u` satisfies `n`.
*/
export const narrow = <N extends Primitive | NarrowerArr | NarrowerObj>(
n: N,
u: unknown,
): u is UnNarrow<N> => {
return _narrow(n, u)
}
export const SOME = Symbol('SOME')
export type NarrowerSome = {
[SOME]: boolean
}
/**
* Decorates a narrower array to indicate narrowing should use the array as a
* set of options instead of asserting the value is an actual array.
*
* @example
* narrow(some('number'), 1) //=> true
* narrow({ optional: some('string', 'undefined') }), { optional: 'yep' }) //=> true
* narrow({ optional: some('string', 'undefined') }), {}) //=> true
*
* @param opts The Narrower types that the value must be one of.
* @returns An array with the SOME symbol set to true.
*/
export const some = <NA extends NarrowerArr>(
...opts: NA
): NA & NarrowerSome => {
return Object.assign(opts, {
[SOME]: true,
})
}
/**
* This does the actual value comparison based on the Narrower schema.
* It leaves out the fancy type inference.
* @private
* @param n The schema.
* @param u The value to validate.
* @returns Whether u matches n.
*/
const _narrow = <N extends Narrower>(n: N, u: unknown): boolean => {
if (typeof n === 'string') {
if (n === typeof u) {
return true
} else {
return false
}
}
if (Array.isArray(n)) {
if (SOME in n) {
return n.some(t => _narrow(t, u))
} else {
if (Array.isArray(u)) {
if (n.length === 0) {
// An empty schema array represents an array with unknown contents.
return true
}
return u.every(v => n.some(t => _narrow(t, v)))
} else {
return false
}
}
}
if (typeof u !== 'object' || u === null) {
return false
}
const o = u as NarrowerObj
return Object.entries(n).every(([k, t]) => _narrow(t, o[k]))
}