Registry / serialization / typeforce

typeforce

JSON →
library0.2.1jsnpmunverified

Typeforce is a JavaScript library designed for biased runtime type checking, offering a comprehensive suite of utilities to enforce data structures and primitive types. As of version 1.18.0, it provides a flexible API for defining complex type schemas, including support for arrays, recursive objects, optional properties (`?`), sum types (`anyOf`), and intersection types (`allOf`). A notable feature is its extensibility through custom type functions, allowing developers to define domain-specific validations. It differentiates itself by offering specialized modules for non-throwing error handling (`typeforce/nothrow`) and asynchronous validation (`typeforce/async`), catering to different error management strategies. While a specific release cadence isn't detailed, its versioning suggests ongoing maintenance and feature development, making it a robust choice for projects requiring strict data validation without relying on static type systems.

npm install typeforce
INSTALL
IMPORT
SIG · TYPEFORCE
T
typeforce
serializationjavascriptv0.2.1
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.

typeforce
const typeforce = require('typeforce')
import typeforce from 'typeforce'
This package is primarily CommonJS. Use `require` for standard Node.js environments.
typeforce.Number
const { Number } = require('typeforce')
import { Number } from 'typeforce'
Primitives like `Number`, `String`, `Array` are properties of the main `typeforce` export. They can be destructured from the `require` call.
typeforce/nothrow
const typeforceNoThrow = require('typeforce/nothrow')
import { nothrow } from 'typeforce'
The non-throwing version is a separate entry point. It's imported directly from its path, not as a named export from the main package.

This quickstart demonstrates basic, recursive, custom, and strict type checking, along with the no-throw variant and performance tips like precompilation.

var typeforce = require('typeforce'); var typeforceNoThrow = require('typeforce/nothrow'); // Define some data var user = { id: 123, name: 'Alice' }; var product = { id: 456, price: 10.99 }; var inventory = [user, product]; var configTuple = ['development', 8080]; // Basic type checking for primitives typeforce('Array', inventory); // OK typeforce('Number', 123); // OK // Array of a specific type (e.g., objects with an ID and a string name) typeforce(typeforce.arrayOf({ id: 'Number', name: 'String' }), [user]); // Recursive type templating for objects with optional properties typeforce({ id: 'Number', name: '?String', price: '?Number' }, product); // Sum types (anyOf) and intersection types (allOf) typeforce(typeforce.anyOf('String', 'Number'), 'foobar'); // 'foobar' is String typeforce(typeforce.allOf({ x: typeforce.Number }, { y: typeforce.String }), { x: 1, y: '2' }); // Both properties must match // Custom type definition (e.g., a specific length string) function HexString32(value) { return typeforce.String(value) && /^[0-9a-fA-F]{32}$/.test(value); } typeforce(HexString32, 'a0b1c2d3e4f5a0b1c2d3e4f5a0b1c2d3'); // OK! // Using the non-throwing version for graceful error handling var potentiallyBadValue = 'this is not a number'; if (!typeforceNoThrow(typeforceNoThrow.Number, potentiallyBadValue)) { console.log(`Error caught by no-throw: ${typeforceNoThrow.error.message}`); } // Protip: use precompiled types for performance on repeated checks var compiledSchema = typeforce.compile({ id: typeforce.Number, timestamp: typeforce.Number }); compiledSchema({ id: 1, timestamp: Date.now() }); // Fast check! // Protip: enforce strictness to disallow extra properties typeforce({ a: 'Number' }, { a: 1 }, true); // OK try { typeforce({ a: 'Number' }, { a: 1, b: 2 }, true); // This will throw an error } catch (e) { console.log(`Strict check error: ${e.message}`); }
Debug
Known issues
gotchaThe `quacksLike` type relies on the `Function.name` property, which can be mangled by transpilers like UglifyJS. This can lead to unexpected type validation failures in minified production builds.
fix
Avoid `quacksLike` if your codebase is minified with name mangling, or ensure your build configuration preserves `Function.name` for relevant classes. Consider using alternative structural checks if possible.
affects: >=1.0.0
gotchaException messages may change between patch versions as underlying behaviors are refined. Relying on the exact text of error messages in tests or logic is fragile.
fix
Do not depend on verbatim error message strings. Instead, check for the presence of an error or the general type of error (e.g., `TypeError`) if specific error handling is required. Use the `typeforce/nothrow` module for cleaner conditional logic based on validation success/failure.
affects: >=1.0.0
gotchaWhen using typeforce with strictness (`typeforce(schema, value, true)`), any properties in the `value` that are not explicitly defined in the `schema` will cause a `TypeError` to be thrown. This is intended behavior for whitelisting properties.
fix
Ensure your schema comprehensively defines all expected properties if strict mode is enabled. If properties are optional, mark them with `?Type` (e.g., `?String`) in the schema. For properties that can be anything, define them with `typeforce.any` or `typeforce.Object` as appropriate.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Expected Number, got Array
Attempting to validate a value against an incorrect primitive type.
fix
Ensure the type string or type object provided to `typeforce` accurately reflects the expected type of the `value` being validated. For example, `typeforce('Array', someArray)` instead of `typeforce('Number', someArray)`.
TypeError: Unexpected property 'y' of type Number
Using strict mode for object validation (`typeforce(schema, value, true)`) where `value` contains properties not declared in `schema`.
fix
If extra properties are allowed, remove the `true` argument for strictness. If they are not allowed, ensure your schema lists all permissible properties, using `?Type` for optional ones.
TypeError: Expected property "0" of type Number, got String 'not a number'
A value in a tuple (fixed-length array) does not match the type specified for its position.
fix
Check the order and types of elements in the array being validated against `typeforce.tuple()`. Each element must precisely match the corresponding type in the tuple definition.
Oops, Expected Number, got String foobar
The `typeforce/nothrow` module was used, and a type validation failed, leading to the error message being stored in `typeforce.error.message`.
fix
This is often expected behavior for `typeforce/nothrow`. The fix involves checking the return value of the `typeforceNoThrow` call; if it's `false`, then `typeforceNoThrow.error.message` will contain the validation failure reason.
Upgrade
Version history
0.2.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
5 hits · last 30 days
node
4
OpenAI (training)
1
Resources
typeforce — npm install typeforce · libregistry