Registry / serialization / typanion

typanion

JSON →
library3.14.0jsnpmunverified

Typanion is a lean, type-safe runtime TypeScript validator library with zero external runtime dependencies. It excels at validating complex, nested data structures and provides strong type inference, which allows TypeScript to refine types based on successful validation. Unlike some alternatives, Typanion emphasizes a functional and tree-shakeable API, making it efficient for bundlers. It provides detailed error reports and supports coercions, enabling data transformation during validation. While it may not have the extensive ecosystem of libraries like Zod or Yup, its core differentiators lie in its minimal footprint, functional design, and robust TypeScript inference. Currently, in version 3.14.0, its release cadence appears less frequent, suggesting a focus on stability over rapid iteration, with the last major activity around two years ago.

npm install typanion
INSTALL
IMPORT
SIG · TYPANION
T
typanion
serializationjavascriptv3.14.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

t
import * as t from 'typanion'
const t = require('typanion')
The primary API is exposed as a namespace import, commonly aliased as `t`. While CJS `require` can work, ESM `import * as t` is the idiomatic and type-safe approach, especially with TypeScript.
isString, isNumber, isObject
import { isString, isNumber, isObject } from 'typanion'
import { t.isString } from 'typanion'
While `t` is the common namespace import, individual predicates like `isString` can also be directly imported for better tree-shaking and explicit usage in some bundlers or environments.
Coercion
import { Coercion } from 'typanion'
type Coercion = any[]
The `Coercion` type is used when enabling data coercion during validation. It's an internal type representing operations to be applied, typically used with the `{ coercions }` option in validation predicates.

This quickstart demonstrates how to define a schema for a user object, validate both valid and invalid data, collect detailed error messages, leverage TypeScript's type inference upon successful validation, and briefly showcases a coercion example.

import * as t from 'typanion'; // Define a schema for a user object const isUser = t.isObject({ id: t.isNumber(), name: t.isString(), email: t.isOptional(t.isString()), age: t.cascade(t.isNumber(), [t.isInteger(), t.isInInclusiveRange(0, 120)]), roles: t.isArray(t.isString(), { maxLength: 3 }), isActive: t.isBoolean(), }); // Example valid data const validUserData = { id: 123, name: 'Alice', email: 'alice@example.com', age: 30, roles: ['admin', 'editor'], isActive: true, }; // Example invalid data const invalidUserData = { id: 'abc', // Should be number name: 123, // Should be string age: 150, // Out of range roles: ['guest', 'viewer', 'reporter', 'qa'], // Too many roles unknownProp: 'oops' // Extraneous property (fails by default) }; interface User { id: number; name: string; email?: string; age: number; roles: string[]; isActive: boolean; } // Validate valid data const errorsForValid: string[] = []; if (isUser(validUserData, { errors: errorsForValid })) { console.log('Valid user data:', validUserData); // TypeScript knows validUserData is now of type User const user: User = validUserData; console.log(user.name); } else { console.error('Validation failed for valid data:', errorsForValid); } console.log('\n--- Attempting to validate invalid data ---'); // Validate invalid data const errorsForInvalid: string[] = []; if (isUser(invalidUserData, { errors: errorsForInvalid })) { console.log('Invalid user data (unexpected success):', invalidUserData); } else { console.error('Validation failed for invalid data:'); errorsForInvalid.forEach(error => console.error(`- ${error}`)); // TypeScript still considers invalidUserData as 'unknown' here // because validation failed. } // Example with coercion (though not typical for this schema) const isCoercibleNumber = t.applyCoercion(t.isNumber(), t.isString()); const coercions: t.Coercion[] = []; const potentiallyNumber = '42'; if (isCoercibleNumber(potentiallyNumber, { coercions })) { for (const [p, op] of coercions) op(); console.log('\nCoerced value:', potentiallyNumber); // will be 42 (number) const num: number = potentiallyNumber; console.log(typeof num); // 'number' } else { console.error('Coercion failed'); }
Debug
Known issues
gotchaWhen validating objects, `typanion` is strict by default and will report errors for extraneous properties not defined in the schema. This differs from some other validators that might ignore unknown properties.
fix
To allow extraneous properties, pass `extra: t.isUnknown()` or a specific schema for extra properties to `t.isObject` (e.g., `t.isObject({ /* ... */ }, { extra: t.isUnknown() })` or `t.isObject({ /* ... */ }, { extra: t.isDict(t.isUnknown()) })`).
affects: >=3.0
gotchaThe `isDate()` predicate has known limitations regarding ISO8601 string parsing and does not natively support milliseconds, which can lead to unexpected validation failures for certain date formats.
fix
For stricter date validation, consider using `t.cascade` with a custom regex predicate (e.g., `t.isString()` combined with `t.matches()` for ISO8601) before `t.isDate()`, or implement custom date parsing logic if milliseconds are critical. (Refer to GitHub issue #39 and #36).
affects: >=3.0
gotchaWhen using `t.cascade()` with `isHexColor`, the predicate may not be supported directly, leading to validation issues for hex color strings.
fix
Instead of `isHexColor`, which might be missing or unsupported in `cascade`, use `t.isString()` combined with `t.matches(/^#[0-9a-fA-F]{3,6}$/)` for basic hex color string validation. (Refer to GitHub issue #41).
affects: >=3.0
gotchaUnexpected type widening can occur when using nested `isEnum` predicates, potentially leading to less precise type inference than expected in complex schemas.
fix
Carefully review the inferred types when using deeply nested `isEnum`. If type widening occurs, consider breaking down complex schemas or using explicit type assertions after validation to enforce the desired type. (Refer to GitHub issue #14).
affects: >=3.0
Errors
Common errors & fixes
Validation failed for path: <path>. Expected <type>, received <other_type>.
An input value did not match the expected type or structure defined by the schema.
fix
Inspect the `errors` array returned by the validation function for detailed messages. Adjust the input data to conform to the schema or refine the schema to accurately reflect the expected data shape. For example, if 'Expected number, received string' ensure the field is parsed as a number before validation.
TypeError: (0 , typanion_1.isObject) is not a function
Incorrect import of predicate functions, often due to mixing CommonJS `require` with ESM named imports or attempting to destructure `t` itself.
fix
Ensure you are using `import * as t from 'typanion'` and accessing predicates as `t.isObject` or explicitly named imports `import { isObject } from 'typanion'`. Avoid `const { isObject } = require('typanion')` if the package is primarily ESM.
Argument of type 'string' is not assignable to parameter of type 'number'.
Attempting to assign a value that failed a `typanion` predicate (e.g., `t.isNumber()`) to a TypeScript type that expects the validated type.
fix
Wrap the code that uses the validated value within the `if (validator(value))` block. `typanion` uses type predicates, so TypeScript's type narrowing only applies inside the conditional block where validation is successful. If coercion is used, ensure `coercions` are flushed.
Upgrade
Version history
3.14.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
7 hits · last 30 days
node
6
OpenAI (training)
1
Resources
typanion — npm install typanion · libregistry