schema/items/nullable.ts

30 lines
789 B
TypeScript

import SchemaItem from "../SchemaItem"
import { SchemaInfer, ValidationResult } from "../types"
export default class SchemaNullable<Type extends SchemaItem> extends SchemaItem<SchemaInfer<Type> | undefined> {
public constructor(public readonly child: Type) { super(arguments) }
public unwrap() {
return this.child
}
public parse(input: unknown, options?: { fast?: boolean }): ValidationResult<SchemaInfer<Type>> {
if (this.isNull(input)) {
return {
valid: true,
object: undefined
}
}
return this.child.parse(input)
}
public override isOfType(input: unknown): input is SchemaInfer<Type> | undefined {
return Array.isArray(input)
}
private isNull(value: unknown): value is undefined | null {
return typeof value === 'undefined' || value === null
}
}