{"id":12223,"library":"typeforce","title":"typeforce - Runtime Type Checking","description":"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.","status":"active","version":"1.18.0","language":"javascript","source_language":"en","source_url":"https://github.com/dcousens/typeforce","tags":["javascript","typeforce","types","typechecking","type","exceptions","force"],"install":[{"cmd":"npm install typeforce","lang":"bash","label":"npm"},{"cmd":"yarn add typeforce","lang":"bash","label":"yarn"},{"cmd":"pnpm add typeforce","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This package is primarily CommonJS. Use `require` for standard Node.js environments.","wrong":"import typeforce from 'typeforce'","symbol":"typeforce","correct":"const typeforce = require('typeforce')"},{"note":"Primitives like `Number`, `String`, `Array` are properties of the main `typeforce` export. They can be destructured from the `require` call.","wrong":"import { Number } from 'typeforce'","symbol":"typeforce.Number","correct":"const { Number } = require('typeforce')"},{"note":"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.","wrong":"import { nothrow } from 'typeforce'","symbol":"typeforce/nothrow","correct":"const typeforceNoThrow = require('typeforce/nothrow')"}],"quickstart":{"code":"var typeforce = require('typeforce');\nvar typeforceNoThrow = require('typeforce/nothrow');\n\n// Define some data\nvar user = { id: 123, name: 'Alice' };\nvar product = { id: 456, price: 10.99 };\nvar inventory = [user, product];\nvar configTuple = ['development', 8080];\n\n// Basic type checking for primitives\ntypeforce('Array', inventory); // OK\ntypeforce('Number', 123);      // OK\n\n// Array of a specific type (e.g., objects with an ID and a string name)\ntypeforce(typeforce.arrayOf({ id: 'Number', name: 'String' }), [user]);\n\n// Recursive type templating for objects with optional properties\ntypeforce({ id: 'Number', name: '?String', price: '?Number' }, product);\n\n// Sum types (anyOf) and intersection types (allOf)\ntypeforce(typeforce.anyOf('String', 'Number'), 'foobar'); // 'foobar' is String\ntypeforce(typeforce.allOf({ x: typeforce.Number }, { y: typeforce.String }), { x: 1, y: '2' }); // Both properties must match\n\n// Custom type definition (e.g., a specific length string)\nfunction HexString32(value) {\n  return typeforce.String(value) && /^[0-9a-fA-F]{32}$/.test(value);\n}\ntypeforce(HexString32, 'a0b1c2d3e4f5a0b1c2d3e4f5a0b1c2d3'); // OK!\n\n// Using the non-throwing version for graceful error handling\nvar potentiallyBadValue = 'this is not a number';\nif (!typeforceNoThrow(typeforceNoThrow.Number, potentiallyBadValue)) {\n  console.log(`Error caught by no-throw: ${typeforceNoThrow.error.message}`);\n}\n\n// Protip: use precompiled types for performance on repeated checks\nvar compiledSchema = typeforce.compile({ \n  id: typeforce.Number,\n  timestamp: typeforce.Number\n});\ncompiledSchema({ id: 1, timestamp: Date.now() }); // Fast check!\n\n// Protip: enforce strictness to disallow extra properties\ntypeforce({ a: 'Number' }, { a: 1 }, true); // OK\ntry {\n  typeforce({ a: 'Number' }, { a: 1, b: 2 }, true); // This will throw an error\n} catch (e) {\n  console.log(`Strict check error: ${e.message}`);\n}","lang":"javascript","description":"This quickstart demonstrates basic, recursive, custom, and strict type checking, along with the no-throw variant and performance tips like precompilation."},"warnings":[{"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.","message":"The `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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"Exception 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"When 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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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)`.","cause":"Attempting to validate a value against an incorrect primitive type.","error":"TypeError: Expected Number, got Array"},{"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.","cause":"Using strict mode for object validation (`typeforce(schema, value, true)`) where `value` contains properties not declared in `schema`.","error":"TypeError: Unexpected property 'y' of type Number"},{"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.","cause":"A value in a tuple (fixed-length array) does not match the type specified for its position.","error":"TypeError: Expected property \"0\" of type Number, got String 'not a number'"},{"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.","cause":"The `typeforce/nothrow` module was used, and a type validation failed, leading to the error message being stored in `typeforce.error.message`.","error":"Oops, Expected Number, got String foobar"}],"ecosystem":"npm"}