shelving
Version:
Toolkit for using data in JavaScript.
51 lines (50 loc) • 2.19 kB
TypeScript
import type { ImmutableArray } from "../util/array.js";
import type { SchemaOptions } from "./Schema.js";
import { Schema } from "./Schema.js";
/** Allowed options for `ArraySchema` */
export interface ArraySchemaOptions<T> extends SchemaOptions {
/** The default value */
readonly value?: ImmutableArray;
/** A schema all the array items in the value must conform to */
readonly items: Schema<T>;
/** Minimum number of items. */
readonly min?: number;
/** Maximum number of items. */
readonly max?: number;
/** Whether to deduplicate the items. */
readonly unique?: boolean;
/** Separator is used */
readonly separator?: string | RegExp;
}
/**
* Define a valid array.
*
* Validates arrays and ensures the array's items match a specified format.
* Only returns a new instance of the object if it changes (for immutability).
*
* @example
* const schema = new ArraySchema({ min: 1, max: 2, default: [10,11,12], required: true });
* schema.validate([1,2,3], schema); // Returns [1,2,3]
* schema.validate(undefined, schema); // Returns [10,11,12] (due to value)
* schema.validate([4,5,6,7], schema); // Returns [4,5,6] (due to max)
* schema.validate(9999, schema); // Throws Invalid('Must be array')
* schema.validate([], schema); // Throws Required
* schema.validate([1,2], schema); // Throws Invalid('Needs at least 3 items')
*
* @example
* const schema = new ArraySchema({ schema: Array });
* schema.validate(["a", "a"], schema); // Returns ["a", "a"]
* schema.validate(["a", null], schema); // Throws Invalids({ "1": Invalid('Must be a string') });
*/
export declare class ArraySchema<T> extends Schema<ImmutableArray<T>> {
readonly value: ImmutableArray<T>;
readonly items: Schema<T>;
readonly unique: boolean;
readonly min: number;
readonly max: number;
readonly separator: string | RegExp;
constructor({ items, one, many, title, placeholder, unique, min, max, separator, value, ...options }: ArraySchemaOptions<T>);
validate(unsafeValue?: unknown): ImmutableArray<T>;
}
/** Valid array with specifed items. */
export declare const ARRAY: <T>(items: Schema<T>) => ArraySchema<T>;