-
Notifications
You must be signed in to change notification settings - Fork 5
/
enum.ts
37 lines (32 loc) · 939 Bytes
/
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
import { createFail, setupInternalRuntype, Runtype } from './runtype'
import { debugValue } from './runtypeError'
type EnumObject = { [key: string]: string | number }
/**
* Any value defined in the enumObject.
*/
function enumRuntype<T extends EnumObject, S extends keyof T>(
enumObject: T,
): Runtype<T[S]> {
return setupInternalRuntype(
(v, failOrThrow) => {
// use the fast reverse lookup of number enums to check whether v is a
// value of the enum
if (
typeof v === 'number' &&
(enumObject as any)[v as any] !== undefined
) {
return (v as unknown) as T[S]
}
if (Object.values(enumObject).indexOf(v as any) !== -1) {
return v as T[S]
}
return createFail(
failOrThrow,
`expected a value that belongs to the enum ${debugValue(enumObject)}`,
v,
)
},
{ isPure: true },
)
}
export { enumRuntype as enum }