{"id":12756,"library":"superstruct","title":"Superstruct Data Validation","description":"Superstruct is a robust and composable library for validating data in JavaScript and TypeScript, designed to provide a simple yet powerful way to define data schemas and enforce their integrity. Currently stable at version 2.0.2, the library maintains an active release cadence, frequently publishing patches to address type resolution, minor bugs, and improve compatibility, as seen with recent 2.0.x releases. Its core differentiator lies in its idiomatic JavaScript API, making it easy to define complex data structures using plain objects and functions, rather than relying on class-based or decorator-heavy approaches. Superstruct focuses on clear error reporting and type inference, integrating seamlessly into TypeScript projects to provide compile-time type safety alongside runtime validation. It's particularly useful in API development, configuration parsing, and any scenario requiring reliable data ingress.","status":"active","version":"2.0.2","language":"javascript","source_language":"en","source_url":"git://github.com/ianstormtaylor/superstruct","tags":["javascript","api","array","assert","cast","check","checker","collection","data","typescript"],"install":[{"cmd":"npm install superstruct","lang":"bash","label":"npm"},{"cmd":"yarn add superstruct","lang":"bash","label":"yarn"},{"cmd":"pnpm add superstruct","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Superstruct v2 is primarily designed for ESM. While CJS usage is possible, explicit type declarations for CommonJS may require specific NodeNext configurations, or lead to module resolution issues.","wrong":"const { object, string, number } = require('superstruct')","symbol":"object","correct":"import { object, string, number } from 'superstruct'"},{"note":"Most utilities like `assert` and `validate` are named exports from the main package. `StructError` is also a named export for error handling.","wrong":"import assert from 'superstruct/assert'","symbol":"assert","correct":"import { assert, StructError } from 'superstruct'"},{"note":"The `Struct` type is used for TypeScript type annotations and should be imported as a type, not a value. Other specific types like `Infer` are also named type imports.","wrong":"import { Struct } from 'superstruct'","symbol":"Struct","correct":"import type { Struct } from 'superstruct'"}],"quickstart":{"code":"import { object, string, number, array, assert, StructError } from 'superstruct';\n\n// Define a struct for a User\nconst User = object({\n  id: string(),\n  name: string(),\n  email: string(),\n  age: number(),\n  roles: array(string()),\n});\n\n// Example valid data\nconst validUser = {\n  id: 'user-123',\n  name: 'John Doe',\n  email: 'john.doe@example.com',\n  age: 30,\n  roles: ['admin', 'editor'],\n};\n\n// Example invalid data\nconst invalidUser = {\n  id: 'user-456',\n  name: 'Jane Smith',\n  email: 'jane.smith@example.com',\n  age: 'twenty-five', // Age should be a number\n  roles: ['viewer', 123] // Roles should be array of strings\n};\n\nconsole.log('Validating validUser...');\ntry {\n  assert(validUser, User);\n  console.log('validUser is valid!');\n} catch (error) {\n  if (error instanceof StructError) {\n    console.error('Validation failed for validUser:', error.message);\n  } else {\n    throw error;\n  }\n}\n\nconsole.log('\\nValidating invalidUser...');\ntry {\n  assert(invalidUser, User);\n  console.log('invalidUser is valid (this should not happen)!');\n} catch (error) {\n  if (error instanceof StructError) {\n    console.error('Validation failed for invalidUser:', error.message);\n    console.error('Failure path:', error.path);\n  } else {\n    throw error;\n  }\n}\n","lang":"typescript","description":"This quickstart demonstrates defining a data schema for a `User` using `object`, `string`, `number`, and `array` structs, then uses `assert` to validate both valid and invalid data against the schema, catching and logging `StructError` for failures."},"warnings":[{"fix":"Review any schemas using `object()`, `type()`, or `record()` that validate properties expecting arrays. Ensure your input data strictly adheres to the defined array types, as previously invalid arrays will now correctly cause validation failures.","message":"Superstruct v2.0.0 introduced a fix for incorrectly passing validation for arrays within `object()`, `type()`, and `record()` structs. If you were relying on the previous, incorrect behavior where invalid arrays might have been accepted, your validation logic will now correctly flag these as errors.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"For Node.js projects, ensure your `tsconfig.json` correctly configures `moduleResolution` (e.g., `bundler` or `node16`) and `module` (e.g., `esnext`, `nodenext`). If using CommonJS, be mindful of `require()` calls and potential interop issues, favoring ESM imports where possible.","message":"Superstruct has progressively moved towards stricter module resolution, especially with 'NodeNext' compatibility. Version 1.0.5-0 (pre-v2) explicitly added file extensions to imports/exports, indicating a shift towards explicit ESM module graphs. This can lead to issues with CommonJS setups or misconfigured TypeScript projects.","severity":"gotcha","affected_versions":">=1.0.5-0"},{"fix":"If experiencing type resolution issues in a CommonJS project with NodeNext, ensure you are on Superstruct `v2.0.3` or newer. You may also need to adjust your `tsconfig.json` to explicitly handle `d.cts` files or ensure your build setup correctly processes CJS type definitions.","message":"With NodeNext type resolution, users migrating or using Superstruct in CommonJS environments might encounter TypeScript errors related to type declaration files (`d.cts`). Versions 2.0.3-0 and 2.0.3-1 specifically address fixes for these scenarios.","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":"Migrate your import statements to ES Modules syntax: `import { object } from 'superstruct'`. If you are in a Node.js CJS module, you may need to ensure your `package.json` specifies `\"type\": \"commonjs\"` and potentially configure your build system for interop.","cause":"Attempting to use CommonJS `require()` syntax in an ESM module context, or when the `superstruct` package is treated as an ESM module.","error":"TypeError: require is not a function"},{"fix":"Verify `superstruct` is installed. Check your `tsconfig.json` for `moduleResolution` (e.g., `\"node16\"` or `\"bundler\"`) and `module` (e.g., `\"esnext\"` or `\"nodenext\"`). Ensure your TypeScript version is up-to-date (>=4.7 for NodeNext features).","cause":"TypeScript compiler cannot locate the package or its types, often due to incorrect module resolution settings, or an outdated TypeScript version that doesn't fully support NodeNext module features.","error":"TS2307: Cannot find module 'superstruct' or its corresponding type declarations."},{"fix":"Inspect the `error.path` and `error.value` properties of the `StructError` to identify the problematic data point. Adjust the input data to conform to the schema's type expectations, or modify the schema if the data structure has genuinely changed.","cause":"A runtime validation error indicating that a value for a specific path in the data does not match the expected type defined in the Superstruct schema.","error":"StructError: At path \"age\" expected a number but received \"twenty-five\""}],"ecosystem":"npm"}