Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/typeguardkit/mod.ts>ArrayAsserter

A TypeScript module to help construct type assertion functions and type guards.
Latest
class ArrayAsserter
Re-export
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 strings.

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
>;

Constructors

new
ArrayAsserter(
typeName: string,
elementAsserter: ElementAsserter,
)

Type Parameters

ElementAsserter extends Asserter<unknown>

Properties

readonly
maxLength: number | null
readonly
minLength: number | null
readonly
mustBeASet: boolean
readonly
rules: ReadonlyArray<ArrayAsserterRule<Asserted<ElementAsserter>>>
readonly
typeName: string

Methods

assert(value: unknown, valueName?: string): Array<Asserted<ElementAsserter>>
validate(value: Array<Asserted<ElementAsserter>>): string[]