32 lines
874 B
TypeScript
32 lines
874 B
TypeScript
import SchemaItem from '../SchemaItem'
|
|
|
|
export type EnumLike = {
|
|
[k: string]: string | number
|
|
[n: number]: string
|
|
}
|
|
|
|
export default class SchemaEnum<E extends EnumLike> extends SchemaItem<E[keyof E]> {
|
|
|
|
private type: 'string' | 'number' = 'string'
|
|
|
|
public constructor(private templateEnum: E) {
|
|
super()
|
|
|
|
// get the type of Enum used (Number enums have reverse maping while string enums don't)
|
|
const firstValue = Object.values(templateEnum)[0]
|
|
if (typeof firstValue === 'number' || typeof templateEnum[firstValue] === 'number') {
|
|
this.type = 'number'
|
|
}
|
|
|
|
// test above === numebr
|
|
this.validations.push({
|
|
fn: (input) => Object.values(this.templateEnum).includes(input),
|
|
message: `Input is not part of ${templateEnum.constructor.name}`
|
|
})
|
|
}
|
|
|
|
public override isOfType(input: unknown): input is E[keyof E] {
|
|
return typeof input === this.type
|
|
}
|
|
}
|