-
-
Notifications
You must be signed in to change notification settings - Fork 63
/
enum.ts
32 lines (26 loc) 路 921 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
import { Type } from "../type.ts";
import type { ArgumentValue } from "../types.ts";
import { InvalidTypeError } from "../../flags/_errors.ts";
/** Enum type. Allows only provided values. */
export class EnumType<TValue extends string | number | boolean>
extends Type<TValue> {
private readonly allowedValues: ReadonlyArray<TValue>;
constructor(values: ReadonlyArray<TValue> | Record<string, TValue>) {
super();
this.allowedValues = Array.isArray(values) ? values : Object.values(values);
}
public parse(type: ArgumentValue): TValue {
for (const value of this.allowedValues) {
if (value.toString() === type.value) {
return value;
}
}
throw new InvalidTypeError(type, this.allowedValues.slice());
}
public override values(): Array<TValue> {
return this.allowedValues.slice();
}
public override complete(): Array<TValue> {
return this.values();
}
}