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

x/typeguardkit/mod.ts>StringAsserter

A TypeScript module to help construct type assertion functions and type guards.
Latest
class StringAsserter
implements Asserter<string>, Validator<string>
import { StringAsserter } from "https://deno.land/x/typeguardkit@0.33.0/mod.ts";

A StringAsserter is an Asserter<string>, with any additional constraints defined by its StringAsserterOptions properties.

The minLength and maxLength options can be used to set the minimum and maximum number of characters (as UTF-16 code units) allowed.

The regex option can be used to specify a regular expression to match against. regex.pattern must be a valid HTML <input> pattern attribute value. It is compiled with ^(?: at the start, )$ at the end, and with the v flag. regex.requirements must not be empty or contain any blank strings.

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 StringAsserterOptions are made accessible as properties of the created StringAsserter.

A StringAsserter is also a Validator<string> with a validate method, which checks only that the provided value meets any constraints defined in the StringAsserterOptions, and returns any issues. This can be used to validate user input client side, where it should already be known that value is a string.

Example:

import { Asserted, StringAsserter } from "typeguardkit";

export const _NonEmptyString = new StringAsserter("NonEmptyString", {
  minLength: 1,
});

export type NonEmptyString = Asserted<typeof _NonEmptyString>;

export const _NumericString = new StringAsserter("NumericString", {
  regex: { pattern: "\\d+", requirements: ["must be numeric"] },
});

export type NumericString = Asserted<typeof _NumericString>;

export const _Palindrome = new StringAsserter("Palindrome", {
  rules: [
    {
      validate(value) {
        if (value.length < 2) {
          return true;
        }

        const forwardValue = value.replace(/[^0-9a-z]/gi, "");
        const backwardValue = forwardValue.split("").reverse().join("");

        return forwardValue === backwardValue;
      },

      requirements: ["must be a palindrome"],
    },
  ],
});

export type Palindrome = Asserted<typeof _Palindrome>;

Constructors

new
StringAsserter(typeName: string, unnamed 1: StringAsserterOptions)

Properties

readonly
maxLength: number | null
readonly
minLength: number | null
readonly
regex: StringAsserterRegex | null
readonly
rules: readonly StringAsserterRule[]
readonly
typeName: string

Methods

assert(value: unknown, valueName?: string): string
validate(value: string): string[]