0.11.0 • Published 4 months ago

@kshramt/runtime-type-validator v0.11.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

@kshramt/runtime-type-validator

A robust and type-safe runtime data validation library for TypeScript.

Table of Contents

  1. Introduction
  2. Installation
  3. Usage

Introduction

@kshramt/runtime-type-validator offers a set of tools for runtime data validation, ensuring that data conforms to expected types and structures.

Installation

Using npm:

npm install @kshramt/runtime-type-validator

Usage

Basic Usage

import { $string, $number } from "@kshramt/runtime-type-validator";

const usernameValidator = $string();
const ageValidator = $number();

Composing Validators

import { $object, $array, $union, $tuple, $literal } from "@kshramt/runtime-type-validator";

const userValidator = $object({
  name: $string(),
  hobbies: $array($string()),
  metadata: $union($string(), $tuple($number(), $literal('info')))
});

Modifiers

import { $object, $readonly, $optional, $opaque } from "@kshramt/runtime-type-validator";

const dataValidator = $object({
  readonlyString: $readonly($string()),
  optionalNumber: $optional($number()),
  readonlyOptionalUserId: $readonly($optional($opaque("UserId", $string()))),
})

Parsing and Error Reporting

import { parse, $infer } from "@kshramt/runtime-type-validator";

{
  const data = {
    name: "John",
    hobbies: ["reading", "swimming"],
    metadata: [42, "info"],
  }
  if(userValidator(data)){ // Use the validator as a type guard.
    validated: $infer<typeof userValidator> = data;
  }
}

{
  const result = parse(userValidator, {
    name: "John",
    hobbies: ["reading", "swimming"],
    metadata: [42, "information"],  // `"infromation"` does not match `$literal("info")`.
  });

  if (!result.success) {
    console.error("Validation failed:", result.path);
  }
}

API Reference

The following are some of the core functions and types provided by "@kshramt/runtime-type-validator":

  • $string, $number, $boolean, $null, $undefined: Basic type validators.
  • $object, $array, $tuple, $union, $literal: Composite type validators.
  • $readonly, $optional, $opaque: Modifiers for creating more specific validators.
  • $typeGuard: Create a validator from a TypeScript type guard.
  • parse: Test a value against a validator and get a detailed error path if validation fails.
0.11.0

4 months ago

0.10.1

9 months ago

0.10.0

9 months ago

0.9.0

9 months ago

0.8.0

9 months ago

0.7.0

9 months ago

0.6.0

9 months ago

0.5.0

9 months ago

0.4.0

9 months ago

0.3.0

9 months ago