UNPKG

@prismicio/types-internal

Version:
52 lines (49 loc) 1.52 kB
import * as t from "io-ts" import { Number } from "./BasicTypes" /** * Creates a custom runtime type for validating that a number falls within a specified range. * * @param min - The minimum value of the range. * @param max - The maximum value of the range. * @param fieldName - The name of the field being validated (used in error messages). * @returns A runtime type representing the number range validation. * * * @example * // Creating a custom runtime type for age validation * const AgeType = numberInRange(18, 99, 'Age'); * * // Valid age * const validAgeResult = AgeType.decode(25); * if (t.isRight(validAgeResult)) { * console.log('Valid age:', validAgeResult.right); // Output: Valid age: 25 * } else { * console.error('Invalid age:', t.left(validAgeResult).map(t.reporter.report)); * } * * @example * // Invalid age * const invalidAgeResult = AgeType.decode(15); * if (t.isRight(invalidAgeResult)) { * console.log('Valid age:', invalidAgeResult.right); * } else { * console.error('Invalid age:', t.left(invalidAgeResult).map(t.reporter.report)); * } */ export default (min: number, max: number, fieldName: string) => Number.pipe( new t.Type<number, number, number>( "numberInRange", (u: unknown): u is number => Number.is(u), (u: number, context) => { if (u > max || u < min) { return t.failure( u, context, `${fieldName} must be a number between ${min} and ${max}`, ) } return t.success(u) }, t.identity, ), )