{"id":12214,"library":"type","title":"JavaScript Type Validation and Coercion","description":"The `type` package offers a suite of runtime validation and processing utilities for fundamental JavaScript types, engineered for environments supporting ECMAScript 3 and higher without implying any transpilation. It specializes in bulletproof input argument normalization and validation, making it highly suitable for validating public API endpoints. The library's current stable version is 2.7.3, released in May 2024, and it follows an irregular release cadence, focusing on maintenance improvements and incremental feature additions like `BigInt` or `Map`/`Set` validation. Its core differentiators include a deep respect for JavaScript's inherent language nature and quirks, offering restricted forms of type coercion that explicitly reject invalid input while intelligently normalizing permissible type deviations. It provides `coerce`, `is`, and `ensure` utilities for various types, enabling developers to confirm types, safely coerce values, or strictly validate them with configurable error handling, including options for optional values and default fallbacks. It's explicitly positioned for basic type checks, recommending more powerful schema-based utilities like AJV or Joi for complex, deeply nested object structures.","status":"active","version":"2.7.3","language":"javascript","source_language":"en","source_url":"https://github.com/medikoo/type","tags":["javascript","type","coercion"],"install":[{"cmd":"npm install type","lang":"bash","label":"npm"},{"cmd":"yarn add type","lang":"bash","label":"yarn"},{"cmd":"pnpm add type","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This package primarily utilizes CommonJS `require()` for accessing its modular sub-path utilities, as demonstrated in its examples.","wrong":"import { ensureString } from 'type/string/ensure';","symbol":"ensureString","correct":"const ensureString = require('type/string/ensure');"},{"note":"CommonJS `require()` is the intended method for importing specific type checking utilities.","wrong":"import { isObject } from 'type/object/is';","symbol":"isObject","correct":"const isObject = require('type/object/is');"},{"note":"Each type utility is exposed via a dedicated CommonJS sub-path.","wrong":"import { ensureNaturalNumber } from 'type/natural-number/ensure';","symbol":"ensureNaturalNumber","correct":"const ensureNaturalNumber = require('type/natural-number/ensure');"}],"quickstart":{"code":"const ensureString        = require('type/string/ensure');\nconst ensureDate          = require('type/date/ensure');\nconst ensureNaturalNumber = require('type/natural-number/ensure');\nconst isObject            = require('type/object/is');\n\nfunction processData(path, options = { min: 0 }) {\n  path = ensureString(path, { errorMessage: \"%v is not a valid path string\" });\n  if (!isObject(options)) {\n    console.warn(\"Options provided were not an object, defaulting to empty.\");\n    options = {};\n  }\n  const min = ensureNaturalNumber(options.min, { default: 0 });\n  const max = ensureNaturalNumber(options.max, { isOptional: true, errorMessage: \"Max value '%v' is not a natural number\" });\n  const startTime = ensureDate(options.startTime, { isOptional: true });\n\n  console.log(`Processing path: ${path}`);\n  console.log(`Min: ${min}, Max: ${max === null ? 'N/A' : max}`);\n  console.log(`Start Time: ${startTime === null ? 'N/A' : startTime.toISOString()}`);\n  // ...further logic based on validated inputs\n}\n\n// Example usage:\nprocessData('/api/resource', { min: 5, max: 10, startTime: new Date() });\nprocessData('/another/path', { min: 'abc' }); // Will throw TypeError for min\nprocessData('/default/options');\n","lang":"javascript","description":"This example demonstrates how to normalize and validate function arguments using various `type` utilities, including string, date, natural number, and object checks, applying options like error messages, optionality, and default values for robust input handling."},"warnings":[{"fix":"For complex object validation, integrate a schema validation library like AJV or Hapi/Joi instead of trying to compose complex validations with `type` utilities.","message":"The `type` package is designed for validating and coercing primitive or simple JavaScript types. For complex, deeply nested object structures or schema-based validation, it's explicitly recommended to use more powerful dedicated schema utilities like AJV or Hapi/Joi, as `type` does not offer this functionality.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Ensure your target environment natively supports the JavaScript features you are using, or implement your own transpilation/polyfill solution if needed. Do not rely on this library for environment compatibility.","message":"The library explicitly states 'No transpilation implied', meaning users should not expect it to polyfill modern JavaScript features. It's written to work in ECMAScript 3+ engines, focusing purely on type validation.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Wrap calls to `*/ensure` in `try...catch` blocks to gracefully handle validation failures, or configure the `isOptional: true` option to accept `null`/`undefined` and `default` option to provide a fallback value.","message":"By default, `*/ensure` utilities throw a `TypeError` if the input value does not meet the specified constraints. This requires explicit error handling (e.g., `try...catch`) or the use of `isOptional` and `default` options to prevent exceptions.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"When using `*/coerce`, always check for `null` in the returned value to determine if coercion was successful. Do not assume a non-null return value without checking.","message":"The `*/coerce` utilities offer 'restricted coercion' and return `null` if a value is not coercible according to their rules, rather than throwing an error. This differs from the error-throwing behavior of `*/ensure`.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Provide a value that satisfies the type constraints of the `*/ensure` utility, or configure the `isOptional: true` option to allow `null`/`undefined`, or set a `default` value.","cause":"An input value failed validation when passed to an `*/ensure` utility without `isOptional` or `default` options.","error":"TypeError: Invalid [type] provided for [name] ([value])"},{"fix":"Ensure your project is configured for CommonJS (e.g., by omitting `\"type\": \"module\"` in `package.json` or by using `.cjs` file extensions for CommonJS files), or use a build tool like Webpack or Rollup to bundle CommonJS modules for an ESM target.","cause":"Attempting to use `require()` statements (CommonJS) in an environment or file configured for ECMAScript Modules (ESM) without proper interoperability setup.","error":"ReferenceError: require is not defined"}],"ecosystem":"npm"}