import { ArrayAsserter } from "https://deno.land/x/typeguardkit@0.33.0/mod.ts";
An ArrayAsserter
is an Asserter
for the Array
type defined by its
elementAsserter
, with any additional constraints defined by its
ArrayAsserterOptions
properties.
The minLength
and maxLength
ArrayAsserterOptions
can be used to set the
minimum and maximum number of elements allowed.
If mustBeASet
is set to true
, each element must be unique (objects are
deeply compared).
The rules
option can be used to specify validate
functions and their
requirements
. Each validate
function should return true
if value
is
valid according to the rule, and false
otherwise. requirements
must not
be empty or contain any blank string
s.
The provided memberAsserter
and ArrayAsserterOptions
are made accessible
as properties of the created ArrayAsserter
.
An ArrayAsserter
is also a Validator
with a validate
method, which
checks only that the provided value
meets any constraints defined in the
ArrayAsserterOptions
, and returns any issues. This can be used to validate
user input client side, where it should already be known that value
meets
the compile-time constraints of the array type.
The array
function can be used to create an ArrayAsserter
without
specifying a typeName
or ArrayAsserterOptions
.
Example:
import { _number, _string, ArrayAsserter, Asserted } from "typeguardkit";
export const _NonEmptyArrayOfString = new ArrayAsserter(
"NonEmptyArrayOfString",
_string,
{ minLength: 1 },
);
export type NonEmptyArrayOfString = Asserted<typeof _NonEmptyArrayOfString>;
export const _ArraySetOfString = new ArrayAsserter(
"ArraySetOfString",
_string,
{ mustBeASet: true },
);
export type ArraySetOfString = Asserted<typeof _ArraySetOfString>;
export const _AscendingArrayOfNumber = new ArrayAsserter(
"AscendingArrayOfNumber",
_number,
{
rules: [
{
validate(value) {
for (let i = 1; i < value.length; i++) {
if (value[i - 1] > value[i]) {
return false;
}
}
return true;
},
requirements: ["must be in ascending order"],
},
],
},
);
export type AscendingArrayOfNumber = Asserted<
typeof _AscendingArrayOfNumber
>;