Superstruct Data Validation

2.0.2 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import { object, string, number, array, assert, StructError } from 'superstruct';

// Define a struct for a User
const User = object({
  id: string(),
  name: string(),
  email: string(),
  age: number(),
  roles: array(string()),
});

// Example valid data
const validUser = {
  id: 'user-123',
  name: 'John Doe',
  email: 'john.doe@example.com',
  age: 30,
  roles: ['admin', 'editor'],
};

// Example invalid data
const invalidUser = {
  id: 'user-456',
  name: 'Jane Smith',
  email: 'jane.smith@example.com',
  age: 'twenty-five', // Age should be a number
  roles: ['viewer', 123] // Roles should be array of strings
};

console.log('Validating validUser...');
try {
  assert(validUser, User);
  console.log('validUser is valid!');
} catch (error) {
  if (error instanceof StructError) {
    console.error('Validation failed for validUser:', error.message);
  } else {
    throw error;
  }
}

console.log('\nValidating invalidUser...');
try {
  assert(invalidUser, User);
  console.log('invalidUser is valid (this should not happen)!');
} catch (error) {
  if (error instanceof StructError) {
    console.error('Validation failed for invalidUser:', error.message);
    console.error('Failure path:', error.path);
  } else {
    throw error;
  }
}

view raw JSON →