### Install Typanion using Yarn Source: https://github.com/arcanis/typanion/blob/main/website/docs/getting-started.md This snippet shows the command to add the Typanion library to your project using the Yarn package manager. ```bash yarn add typanion ``` -------------------------------- ### Using Typanion's assert and as helpers Source: https://github.com/arcanis/typanion/blob/main/website/docs/getting-started.md Demonstrates Typanion's `assert` helper for throwing errors on validation failure and the `as` helper for validating and returning the value, optionally with coercion. ```typescript import * as t from 'typanion'; // Will throw if userData isn't a blogPost t.assert(userData, isBlogPost); // Same, but will also return the value (optionally coerced, see below) const val = t.as(userData, isBlogPost, {throw: true}); ``` -------------------------------- ### Detailed error reporting with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/getting-started.md Explains how to collect detailed validation errors by passing an errors array to the Typanion validator. This allows for more informative error messages when validation fails. ```typescript const errors: string[] = []; if (!isBlogPost(userData, {errors})) { throw new Error(`Validation errors:\n${errors.join(`\n`)}`); } ``` -------------------------------- ### Define a BlogPost schema with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/getting-started.md Demonstrates how to define a data structure for a blog post using Typanion's object and primitive type validators. This schema checks for a title (string), description (string), and published status (boolean). ```typescript import * as t from 'typanion'; const isBlogPost = t.isObject({ title: t.isString(), description: t.isString(), published: t.isBoolean(), }); ``` -------------------------------- ### Validate unknown data with Typanion schema Source: https://github.com/arcanis/typanion/blob/main/website/docs/getting-started.md Shows how to use a Typanion validator (isBlogPost) to check if an unknown data variable conforms to the defined schema. If validation passes, Typanion provides type refinement. ```typescript declare const userData: unknown; if (isBlogPost(userData)) { console.log(userData.title); } ``` -------------------------------- ### Install Typanion Source: https://github.com/arcanis/typanion/blob/main/README.md Installs the Typanion library using Yarn. This is the primary method for adding Typanion to your project. ```bash yarn add typanion ``` -------------------------------- ### Coercing data types with Typanion's as helper Source: https://github.com/arcanis/typanion/blob/main/website/docs/getting-started.md Shows how to use the `coerce: true` option with Typanion's `as` helper to automatically convert compatible data types (e.g., string 'true' to boolean true). Note that coercion may mutate the input data. ```typescript import * as t from 'typanion'; const validatedData = t.as(userData, isBlogPost, {coerce: true, throw: true})) // Will have turned "true" and "false" strings into the proper boolean values console.log(validatedData.published); ``` -------------------------------- ### Infer TypeScript type from Typanion schema Source: https://github.com/arcanis/typanion/blob/main/website/docs/getting-started.md Illustrates how to use Typanion's `InferType` helper to derive a TypeScript type directly from a validation schema, ensuring type safety and preventing outdated type definitions. ```typescript import * as t from 'typanion'; type BlogPost = t.InferType; ``` -------------------------------- ### Validate Port Protocol Source: https://github.com/arcanis/typanion/blob/main/website/docs/examples.md Validates if an unknown value is an integer within the valid port range (1-65535). This uses `applyCascade` to chain multiple validation rules. ```ts const isPort = t.applyCascade(t.isNumber(), [ t.isInteger(), t.isInInclusiveRange(1, 65535), ]); isPort(42000); ``` -------------------------------- ### Validate Object with Specific Field and Dictionary Extras Source: https://github.com/arcanis/typanion/blob/main/website/docs/examples.md Validates if an unknown value is an object that must have a `uid` field of type string, and all other extra fields must be numbers. This is useful for validating data models or configuration objects. ```ts const isModel = t.isObject({ uid: t.isString(), }, { extra: t.isDict(t.isNumber()), }); isModel({uid: `foo`, valA: 12, valB: 24}); ``` -------------------------------- ### Validate Object with Specific Fields and Unknown Extras Source: https://github.com/arcanis/typanion/blob/main/website/docs/examples.md Validates if an unknown value is an object containing a specific `tagName` field with the literal value 'DIV', while allowing any other extra properties. This is useful for validating DOM elements or similar structures. ```ts const isDiv = t.isObject({ tagName: t.isLiteral(`DIV`), }, { extra: t.isUnknown(), }); isDiv({tagName: `div`, appendChild: () => {}}); ``` -------------------------------- ### Define and Use a Movie Schema with Typanion Source: https://github.com/arcanis/typanion/blob/main/README.md Demonstrates how to define a schema for a movie object using Typanion's `isObject` and `isString` functions. It shows how to validate an unknown value against this schema and access properties if validation passes. ```typescript import * as t from 'typanion'; const isMovie = t.isObject({ title: t.isString(), description: t.isString(), }); const userData = JSON.parse(input); if (isMovie(userData)) { console.log(userData.title); } ``` -------------------------------- ### Typanion Schema Validation with Coercion Source: https://github.com/arcanis/typanion/blob/main/README.md Shows how to use Typanion for schema validation while applying coercions to the input data. The `coercions` array collects operations that can be applied to transform the data if validation succeeds. ```typescript const userData = JSON.parse(input); const coercions: Coercion[] = []; if (isMovie(userData, {coercions})) { // Coercions aren't flushed by default for (const [p, op] of coercions) op(); // All relevant fields have now been coerced // ... } ``` -------------------------------- ### Typanion Schema Validation with Error Reporting Source: https://github.com/arcanis/typanion/blob/main/README.md Illustrates how to perform schema validation with Typanion and capture detailed error messages. An array is passed to the schema function to collect any validation errors encountered. ```typescript const userData = JSON.parse(input); const errors: string[] = []; if (!isMovie(userData, {errors})) { console.log(errors); } ``` -------------------------------- ### isOneOf validation with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/helpers.md The `isOneOf` predicate validates that a value matches any of the provided specifications, inferring the type as a union of all candidates. An optional `exclusive` flag can enforce that only one variant matches. ```ts const validate = t.isOneOf([specA, specB], {exclusive?}); ``` -------------------------------- ### Derive TypeScript Type from Typanion Schema Source: https://github.com/arcanis/typanion/blob/main/README.md Demonstrates how to infer a TypeScript type directly from a Typanion schema using `t.InferType`. This allows for strong typing of data that conforms to the schema, improving code safety and maintainability. ```typescript import * as t from 'typanion'; const isMovie = t.isObject({ title: t.isString(), description: t.isString(), }); type Movie = t.InferType; // Then just use your alias: const printMovie = (movie: Movie) => { // ... }; ``` -------------------------------- ### Cascade validation with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/helpers.md The `cascade` predicate ensures values match a primary spec and then runs follow-up validations. It handles coercion by applying it before and reverting after cascading predicates execute, which can affect setters. ```ts const validate = t.cascade(spec, [specA, specB, ...]); ``` -------------------------------- ### isNullable predicate with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/helpers.md The `isNullable` predicate adds `null` as an acceptable value for a given specification, simplifying the handling of potentially null data. ```ts const validate = t.isNullable(spec); ``` -------------------------------- ### isOptional predicate with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/helpers.md The `isOptional` predicate marks `undefined` as an allowed value for a given specification, useful for optional fields or parameters. ```ts const validate = t.isOptional(spec); ``` -------------------------------- ### Define Nested Schemas with Typanion Source: https://github.com/arcanis/typanion/blob/main/README.md Shows how to define complex, nested schemas using Typanion, such as validating an array of actor objects within a movie object. This highlights Typanion's capability to handle intricate data structures. ```typescript import * as t from 'typanion'; const isActor = t.isObject({ name: t.isString(); }); const isMovie = t.isObject({ title: t.isString(), description: t.isString(), actors: t.isArray(isActor), }); ``` -------------------------------- ### Accept Any Value with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Accepts any input without validation or type refinement. By default, forbids undefined and null, but this can be changed with isOptional/isNullable. ```ts const validate = t.isUnknown(); ``` -------------------------------- ### Validate Instance of Constructor with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are instances of a given constructor. ```ts const validate = t.isInstanceOf(constructor); ``` -------------------------------- ### Typanion: Require Specific Object Keys Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Ensures that an object includes all specified keys. Similar to `hasMutuallyExclusiveKeys`, it supports options for defining what constitutes a missing key. ```ts import * as t from 'typanion'; declare const keys: Array; declare const options: {missingIf: t.MissingType}; const validate = t.hasRequiredKeys(keys, options); ``` -------------------------------- ### Typanion: Check Minimum Numeric Value Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Verifies that a numeric value is greater than or equal to a specified number. This is a basic range check for numerical data. ```ts const validate = t.isAtLeast(n); ``` -------------------------------- ### Validate Tuple with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are tuples where items match specified schemas. Supports string input with a delimiter when coercion is enabled. ```ts const validate = t.isTuple(values, {delimiter?}); ``` -------------------------------- ### Validate Dictionary with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are JavaScript objects with arbitrary fields matching a schema. The 'keys' option can apply a schema to the keys. ```ts const validate = t.isDict(values, {keys?}); ``` -------------------------------- ### Validate Partial Object with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Similar to isObject, but allows any number of extraneous properties. ```ts const validate = t.isPartial(props); ``` -------------------------------- ### Typanion: Disallow Specific Object Keys Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Ensures that an object does not contain any of the specified keys. It accepts an array of forbidden keys and optional configuration for handling missing keys. ```ts import * as t from 'typanion'; declare const forbiddenKey1: string; declare const forbiddenKey2: string; declare const forbiddenKeyN: Array; declare const options: {missingIf: t.MissingType}; const validate = t.hasForbiddenKeys([forbiddenKey1, forbiddenKey2, ...forbiddenKeyN], options); ``` -------------------------------- ### Typanion: Ensure At Least One Key Exists Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Validates that an object contains at least one key from a provided list. It uses the same `missingIf` option as other key-related predicates to define missingness. ```ts import * as t from 'typanion'; declare const keys: Array; declare const options: {missingIf: t.MissingType}; const validate = t.hasAtLeastOneKey(keys, options); ``` -------------------------------- ### Check if value matches a regular expression Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md The `matchesRegExp` predicate validates that a value matches a provided regular expression. ```TypeScript const validate = t.matchesRegExp(); ``` -------------------------------- ### Typanion: Check Maximum Numeric Value Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Confirms that a numeric value is less than or equal to a specified number. It's used for enforcing upper bounds on numerical inputs. ```ts const validate = t.isAtMost(n); ``` -------------------------------- ### Validate String with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are regular strings. ```ts const validate = t.isString(); ``` -------------------------------- ### Validate Array with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are arrays where all elements match a specified schema. Supports string input with a delimiter when coercion is enabled. ```ts const validate = t.isArray(values, {delimiter?}); ``` -------------------------------- ### Validate Map with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are Map instances. Supports coercion from arrays of tuples. ```ts const validate = t.isMap(keySpec, valueSpec); ``` -------------------------------- ### Typanion: Ensure Mutually Exclusive Object Keys Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Checks that an object contains at most one key from a given list. It allows configuration for how missing keys are interpreted, such as `undefined` or `nil`. ```ts import * as t from 'typanion'; declare const keys: Array; declare const options: {missingIf: t.MissingType}; const validate = t.hasMutuallyExclusiveKeys(keys, options); ``` -------------------------------- ### Validate Set with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are Set instances. Supports coercion from arrays or delimiter-separated strings. ```ts const validate = t.isSet(values, {delimiter?}); ``` -------------------------------- ### Check if string is ISO 8601 date format Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md The `isISO8601` predicate validates that a string represents a date in the ISO 8601 standard format. ```TypeScript const validate = t.isISO8601(); ``` -------------------------------- ### Typanion: Enforce Minimum Length Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Ensures that a value's `length` property is at least a specified minimum value. This is commonly used for validating minimum string or array lengths. ```ts import * as t from 'typanion'; declare const length: number; const validate = t.hasMinLength(length); ``` -------------------------------- ### Typanion: Validate Base64 Encoding Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Checks if a string value is a valid Base64 encoded string. This is useful for validating data that is expected to be in this format. ```ts const validate = t.isBase64(); ``` -------------------------------- ### Check if value is negative Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md The `isNegative` predicate ensures that a value is less than or equal to 0. ```TypeScript const validate = t.isNegative(); ``` -------------------------------- ### Typanion: Validate Hexadecimal Color Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Ensures that a string represents a valid hexadecimal color code. An option is available to allow for an alpha channel (transparency). ```ts const validate = t.isHexColor({alpha?}); ``` -------------------------------- ### Check if string is all lowercase Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md The `isLowerCase` predicate verifies that a string contains only lowercase characters. ```TypeScript const validate = t.isLowerCase(); ``` -------------------------------- ### Validate Object Shape with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are plain objects matching a given property shape. Extraneous properties can be validated with the 'extra' schema. ```ts const validate = t.isObject(props, {extra?}); ``` -------------------------------- ### Typanion: Check Inclusive Numeric Range Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Confirms that a numeric value falls within a specified range, including the endpoints (inclusive). ```ts const validate = t.isInInclusiveRange(a, b); ``` -------------------------------- ### Typanion: Ensure Exact Length Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Validates that a value has a `length` property exactly equal to a specified number. This predicate is useful for enforcing precise string or array lengths. ```ts import * as t from 'typanion'; declare const length: number; const validate = t.hasExactLength(length); ``` -------------------------------- ### Typanion: Validate Key Relationships Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Asserts a specific relationship between keys in an object. If the subject key exists, it enforces a defined relationship (e.g., forbidding or requiring other keys). It supports ignoring certain properties during the check. ```ts import * as t from 'typanion'; declare const subjectKey: string; declare const relationship: t.KeyRelationship; declare const otherKeys: Array; declare const ignore: Array | undefined; const validate = t.hasKeyRelationship(subjectKey, relationship, otherKeys, {ignore}); ``` -------------------------------- ### Validate Boolean with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are booleans. Supports coercion. For specific true/false checks, isLiteral is recommended. ```ts const validate = t.isBoolean(); ``` -------------------------------- ### Check if string is all uppercase Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md The `isUpperCase` predicate verifies that a string contains only uppercase characters. ```TypeScript const validate = t.isUpperCase(); ``` -------------------------------- ### Validate Number with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are numbers. Supports coercion. ```ts const validate = t.isNumber(); ``` -------------------------------- ### Validate Date with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are proper Date instances. Supports coercion from ISO8601 strings or numbers (seconds since epoch). ```ts const validate = t.isDate(); ``` -------------------------------- ### Check if value is positive Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md The `isPositive` predicate ensures that a value is greater than or equal to 0. ```TypeScript const validate = t.isPositive(); ``` -------------------------------- ### Typanion: Validate Integer Type Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Ensures that a value is a safe integer. An option `unsafe` can be enabled to also accept JavaScript's unsafe integers. ```ts const validate = t.isInteger(n, {unsafe?}); ``` -------------------------------- ### Validate JSON Payload with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are JSON strings whose parsed representation matches a validator. Coerces the original value if coercion is enabled. ```ts const validate = t.isPayload(spec); ``` -------------------------------- ### Typanion: Validate Unique Array Items Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Ensures that all items in an array are unique. An optional `map` function can be provided to transform items before comparison. ```ts const validate = t.hasUniqueItems({map?}); ``` -------------------------------- ### Typanion: Enforce Maximum Length Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Validates that a value's `length` property does not exceed a specified maximum value. This is useful for limiting string or array sizes. ```ts import * as t from 'typanion'; declare const length: number; const validate = t.hasMaxLength(length); ``` -------------------------------- ### Validate Literal Value with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are strictly equal to a specified expected value. Useful for Redux actions or similar structures. ```ts const validate = t.isLiteral(value); ``` -------------------------------- ### Check if string is a valid UUID v4 Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md The `isUUID4` predicate ensures that a string is a valid UUID version 4. ```TypeScript const validate = t.isUUID4(); ``` -------------------------------- ### Check if value is valid JSON Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md The `isJSON` predicate ensures that a value is valid JSON. It can optionally validate against a nested schema. This predicate does not support coercion; for coercion, use `isPayload`. ```TypeScript const validate = t.isJSON(schema?); ``` -------------------------------- ### Typanion: Check Exclusive Numeric Range Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/cascading.md Validates that a numeric value falls strictly between two specified numbers (exclusive of the endpoints). ```ts const validate = t.isInExclusiveRange(a, b); ``` -------------------------------- ### Validate Enum with Typanion Source: https://github.com/arcanis/typanion/blob/main/website/docs/predicates/types.md Ensures values are within an allowed set of literals, accepting arrays or records (including TS enums). ```ts enum MyEnum { /* ... */ }; const validate = t.isEnum(MyEnum); ``` ```ts const validate = t.isEnum(values); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.