@grest-ts/schema

中文文档
0.0.101发布于 2026/11/02MITTypeScriptES Module零依赖近 30 天下载 7394

Type-safe schema validation, serialization, and contract definitions for TypeScript

原始使用文档
文档目录5 节
  1. Features
  2. Quick usage example
  3. Contract example
  4. Permissions (reference)
  5. Documentation

Part of the grest-ts framework. Documentation | All packages

@grest-ts/schema

Type-safe runtime validation library for Grest Framework.

Features

  • World fastest stringify, validation, clean and coerce thanks to AOT.
  • Type-safe validators with branded type support
  • Primitive validators (IsString, IsNumber, IsBoolean)
  • Composite validators (IsObject, IsArray, IsUnion, IsDiscriminated)
  • Rich set of branded validators (IsInt, IsEmail, IsUrl, IsDate, etc.)
  • Coercion support for API input parsing
  • Detailed validation error collection with paths
  • Zero runtime overhead branded types
  • Internalization / translations are fully supported via @grest-ts/intl

Quick usage example

import {IsString, IsNumber, IsObject, IsInt, IsEmail, GGIssuesList} from "@grest-ts/schema"

// Define a validator for your type
const IsUser = IsObject({
    id: IsInt,
    name: IsString,
    email: IsEmail,
    age: IsInt.orUndefined
});

// ---
// Parse with coercion and error collection
const result = IsUser.safeParse(data, true) // set last argument to false to skip coercion.
if (result.success === false) {
    // Handle validation errors
    console.log(result.issues.toJSON())
}

// ---
// Type guard - returns boolean
if (IsUser.is(user)) {
    // data is typed as User  (but can contain extra properties, not safe for database insert for example. Use parse instead)
}

// ---
// Assert - throws on validation failure
IsUser.assert(data)

// ---
// Branded types for domain modeling
const IsUserId = IsInt.brand<"UserId">();
const userId = IsUserId.parse(rawId, true); // parse with coercion, throws on error
type tUserId = typeof IsUserId.infer;

Contract example

Type-safe classes with validated input, output, and typed errors:

import {EXISTS, GGContractClass, IsEmail, IsInt, IsObject, IsString, NOT_FOUND} from "@grest-ts/schema"

// Define a contract class with multiple methods
const UserContract = new GGContractClass("User", {
    get: {
        input: IsObject({userId: IsInt}),
        success: IsObject({id: IsInt, name: IsString}),
        errors: [NOT_FOUND]
    },
    create: {
        input: IsObject({name: IsString, email: IsEmail}),
        success: IsObject({id: IsInt, name: IsString}),
        errors: [EXISTS]
    }
});

// Implement the contract
const UserService = UserContract.implement((db) => ({
    async get(data) {
        const user = await db.users.find(data.userId)
        if (!user) throw new NOT_FOUND()
        return user
    },
    async create(data) {
        return db.users.create(data)
    }
}));

// Create instance and call methods - errors are typed!
const userService = new UserService(database);
const result = await userService.get({userId: 123}).asResult();
if (result.success) {
    console.log(result.data.name);  // typed as string
} else {
    console.log(result.type);  // "NOT_FOUND" | "VALIDATION_ERROR" | "SERVER_ERROR"
}

See Contract documentation for custom errors, GGPromise helpers, and more.

Permissions (reference)

Contract methods may declare an optional permission field. The caller's scopes come from the wires the schema .use()s (each smart wire's permissions() resolver) — see @grest-ts/http → "Permissions". Strict mode is per-server: the moment any route on a server declares permission, every route on that server must declare one (use GG_NO_PERMISSIONS for intentionally public routes). The check runs at server start. Exports from @grest-ts/schema:

  • GG_NO_PERMISSIONS — explicit public endpoint.
  • GG_ANY_PERMISSION — any authenticated identity (caller must have at least one scope).
  • A bare string — single OAuth-style scope.
  • {allOf: [...]} / {anyOf: [...]} — AND/OR combinators (non-empty tuples).
  • satisfies(required, scopes) — pure checker used by both the gate and GGPermissionChecker.has(...).
  • GGPermissionChecker — wraps a scope set so allOf/anyOf checks use the same satisfies(...) the gate uses.
  • validatePermission(tree) — well-formedness pass; runs in GGContractClass/GGContractFunction constructors when a permission is set.

For the runtime mechanics — gate placement, transport wiring, and the strict-mode startup check — see @grest-ts/http and @grest-ts/websocket.

Documentation

  • Usage - How to define and use validators
  • Contract - Type-safe RPC contracts with typed errors
  • Codec - Bidirectional data transformation with schema documentation
  • Localization - How to localize error messages.
  • Extending - How to create custom validators

版本与发布记录

@grest-ts/schema 共发布 84 个版本,首次发布于 2026/02/24;过去 12 个月发布了 84 个版本。

版本发布日期距今
0.0.101latest2026/11/0214 天前
0.0.1002026/10/3017 天前
0.0.992026/10/3018 天前
0.0.982026/10/2820 天前
0.0.972026/10/2720 天前
0.0.962026/10/2721 天前

关于 @grest-ts/schema 的常见问题

@grest-ts/schema 是什么?

Type-safe schema validation, serialization, and contract definitions for TypeScript

如何安装 @grest-ts/schema?

在项目目录运行 npm install @grest-ts/schema,或使用 pnpm add / yarn add / bun add。

@grest-ts/schema 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@grest-ts/schema 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@grest-ts/schema 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@grest-ts/schema 可以商用吗?

@grest-ts/schema 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@grest-ts/schema 的下载量有多少?

根据 npm 官方下载统计,@grest-ts/schema 在 2026/10/17 – 2026/11/15 这 30 天内被下载 7,394 次,日均约 246 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@grest-ts/schema 还在维护吗?

最新版本 0.0.101 发布于 2026/11/02(14 天前);至今共发布 84 个版本,其中过去 12 个月发布了 84 个;首次发布于 2026/02/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。