This package offers runtime type validation features.
npm install @kshramt/runtime-type-validator@kshramt/runtime-type-validatorA robust and type-safe runtime data validation library for TypeScript.
1. Introduction
2. Installation
3. Usage
- Basic Usage
- Composing Validators
- Modifiers
- Parsing and Error Reporting
@kshramt/runtime-type-validator offers a set of tools for runtime data validation, ensuring that data conforms to expected types and structures.
Using npm:
``bash`
npm install @kshramt/runtime-type-validator
`typescript
import { $string, $number } from "@kshramt/runtime-type-validator";
const usernameValidator = $string();
const ageValidator = $number();
`
`typescript
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')))
});
`
`typescript
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()))),
})
`
`typescript
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
}
}
{
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);
}
}
`
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.