-
Notifications
You must be signed in to change notification settings - Fork 1
/
enum.ts
47 lines (43 loc) · 1.16 KB
/
enum.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 { makeSimpleSchema, Schema } from "../schema";
import { Validation, ValidationIssue } from "../validation";
export type EnumLike<E> = Record<keyof E, number | string>;
export function nativeEnum<T extends EnumLike<T>>(
e: T,
issues?: Partial<{
required: string;
wrongType: string;
enum: string;
}>
): Schema<T[keyof T], T[keyof T], { type: "enum"; enum: T }> {
type V = Validation<T[keyof T]>;
const entries = new Set(
Object.entries(e)
.filter(([key]) => !Number.isInteger(Number(key)))
.map(([_, value]) => value)
);
return makeSimpleSchema(
(v) => {
if (v === undefined || v === null) {
return new ValidationIssue("required", issues?.required, v) as V;
}
if (typeof v !== "string" && typeof v !== "number") {
return new ValidationIssue(
"wrong_type",
issues?.wrongType,
v,
"string",
"number"
) as V;
}
if (!entries.has(v)) {
return new ValidationIssue(
"enum",
issues?.enum,
v,
...entries.values()
) as V;
}
},
() => ({ type: "enum", enum: e })
);
}