TypeScript Interface Runtime Validator

1.0.2 · active · verified Sun Apr 19

ts-interface-checker is a runtime validation library for TypeScript interfaces, currently stable at version 1.0.2. It works in conjunction with `ts-interface-builder` (a build-time tool) to generate JavaScript modules that encapsulate the structural checks derived from TypeScript interface definitions. This approach allows developers to validate arbitrary JavaScript objects (e.g., parsed JSON from network requests or configuration files) against their TypeScript types at runtime, providing detailed error messages upon failure. The library itself is lightweight and focuses solely on the runtime checking mechanism, making it suitable for environments where type safety beyond compile-time is desired, such as API boundary validation. It supports checking properties, optional fields, and even method call arguments and return values as defined in interfaces. It maintains a stable release cadence for its core functionality.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the full workflow of defining a TypeScript interface, conceptually generating runtime checkers using `ts-interface-builder`, and then utilizing `ts-interface-checker` to validate JavaScript objects against the interface's structure at runtime, including expected error scenarios.

// 1. Define your TypeScript interface (e.g., in `foo.ts`)
// interface Square {
//   size: number;
//   color?: string;
// }

// 2. Generate runtime checker code using ts-interface-builder (build step)
//    npx ts-interface-builder foo.ts
//    This creates `foo-ti.js` or `foo-ti.ts`.
//    The content of `foo-ti.js` would look something like:
/*
// foo-ti.js
import * as t from "ts-interface-checker";
export const Square = t.iface([], {
  "size": "number",
  "color": t.opt("string"),
});
const exportedTypeSuite = { Square };
export default exportedTypeSuite;
*/

// 3. At runtime, import the generated type suite and create checkers.
// For a self-contained example, we'll mock the `foo-ti` module content directly:

// A minimal mock of what `foo-ti.js`'s default export would look like to `createCheckers`
// In a real application, you would `import fooTI from './foo-ti';`
const mockFooTI = {
  Square: { // This structure would be generated by ts-interface-builder
    name: "Square",
    check: (value: any) => {
      if (typeof value !== 'object' || value === null) throw new Error('value is not an object');
      if (typeof value.size !== 'number') throw new Error('value.size is not a number');
      if ('color' in value && typeof value.color !== 'string') throw new Error('value.color is not a string');
    }
  }
};

// Import createCheckers from the library
import { createCheckers } from "ts-interface-checker";

const { Square } = createCheckers(mockFooTI); // Pass in the generated type suite

console.log("Checking valid objects:");
Square.check({ size: 1 });                  // OK
Square.check({ size: 1, color: "green" });  // OK
console.log("Valid objects checked successfully.");

try {
  console.log("\nChecking invalid object (missing property):");
  Square.check({ color: "green" });
} catch (e: any) {
  console.error(`Error: ${e.message}`); // Expected: Error: value.size is not a number
}

try {
  console.log("\nChecking invalid object (wrong property type):");
  Square.check({ size: 4, color: 5 });
} catch (e: any) {
  console.error(`Error: ${e.message}`); // Expected: Error: value.color is not a string
}

view raw JSON →