DEV Community

Alex Spinov
Alex Spinov

Posted on

Typebox Has a Free API That Most Developers Dont Know About

Typebox creates JSON Schema types that also serve as TypeScript types. Define once — get runtime validation AND compile-time type safety.

Define Schemas

import { Type, Static } from "@sinclair/typebox";

const User = Type.Object({
  id: Type.String({ format: "uuid" }),
  name: Type.String({ minLength: 1, maxLength: 100 }),
  email: Type.String({ format: "email" }),
  age: Type.Optional(Type.Integer({ minimum: 0, maximum: 150 })),
  role: Type.Union([Type.Literal("admin"), Type.Literal("user")]),
  tags: Type.Array(Type.String(), { maxItems: 10 })
});

type User = Static<typeof User>;
// { id: string; name: string; email: string; age?: number; role: "admin" | "user"; tags: string[] }
Enter fullscreen mode Exit fullscreen mode

Validate

import { Value } from "@sinclair/typebox/value";

const data = { id: "abc", name: "John", email: "john@example.com", role: "admin", tags: [] };

if (Value.Check(User, data)) {
  // data is typed as User
  console.log(data.name);
}

// Or get errors
const errors = [...Value.Errors(User, data)];
Enter fullscreen mode Exit fullscreen mode

Compile for Performance

import { TypeCompiler } from "@sinclair/typebox/compiler";

const C = TypeCompiler.Compile(User);

const valid = C.Check(data); // 100x faster than Value.Check
const errors = [...C.Errors(data)];
Enter fullscreen mode Exit fullscreen mode

Key Features

  • JSON Schema + TypeScript types from one definition
  • Fastest JSON schema validator
  • Compiled validation for max performance
  • Standard JSON Schema output
  • Zero dependencies

Need to scrape or monitor web data at scale? Check out my web scraping actors on Apify or email spinov001@gmail.com for custom solutions.

Top comments (0)