@decs/typeschema

中文文档
0.12.2发布于 2024/01/21MITTypeScriptESM + CJS零依赖近 30 天下载 1.4万

Universal adapter for schema validation

此软件包已被标记为弃用

TypeSchema has been restructured. Install @typeschema/main or @typeschema/all instead.

原始使用文档
文档目录6 节
  1. Features
  2. Usage
  3. Coverage
  4. Setup
  5. API
  6. Acknowledgements

TypeSchema

TypeSchema

✨ https://typeschema.com ✨
Universal adapter for schema validation


License Bundle size npm downloads GitHub stars

Setup   •   API   •   Coverage   •   GitHub   •   npm   •   Deno


Many libraries rely on some sort of type validation. Their maintainers have the choice of either to:

  1. ⁠Implement their own validation logic: which leads to more code to maintain, and we already have many good solutions out there (e.g. zod, arktype, typia)
  2. Couple their code with a specific validation library: which limits adoption by developers who use another
  3. Support multiple validation libraries: which is a burden to keep up-to-date (e.g. tRPC)

There's no best validation library because there's always a tradeoff. Each developer chooses the library that makes the most sense to them. TypeSchema solves this problem by easily providing option 3: support multiple validation libraries out-of-the-box.

Features

  • 🚀 Decouple from schema validation libraries
  • 🍃 Tiny client footprint, tree-shakeable
  • 🛋️ Easy-to-use, minimal API

Usage

import type {Infer, InferIn, Schema} from '@decs/typeschema';
import {assert, validate, wrap} from '@decs/typeschema';

// Use your favorite validation library, e.g. `zod`, `arktype`, `typia`
const schema: Schema = z.string();
const schema: Schema = type('string');
const schema: Schema = typia.createAssert<string>();

// Extracts the schema type
type Output = Infer<typeof schema>; // `string`
type Input = InferIn<typeof schema>; // `string`

// Returns the wrapped schema with access to all its operations
const wrapped = wrap(schema);
await wrapped.validate('123'); // {success: true, data: '123'}
await wrapped.assert('123'); // '123'

// Returns the validated data or a list of `ValidationIssue`s
await validate(schema, '123'); // {success: true, data: '123'}
await validate(schema, 123); // {success: false, issues: [`ValidationIssue`]}

// Returns the validated data or throws an `AggregateError`
await assert(schema, '123'); // '123'
await assert(schema, 123); // throws `AggregateError`

tRPC

You can use any supported schema on tRPC through the wrap function:

import {wrap} from '@decs/typeschema';
import {initTRPC} from '@trpc/server';
import {object, string} from 'valibot';

// Use your favorite validation library, e.g. `valibot`
const schema = object({name: string()});

const t = initTRPC.create();
const appRouter = t.router({
  hello: t.procedure
    .input(wrap(schema)) // like this
    .query(({input}) => `Hello, ${input.name}!`),
});

Coverage

TypeSchema supports all major schema validation libraries:

ProjectPopularitywrapvalidate
assert
InferInferInExample schema
zodGitHub stars✅✅✅✅z.string()
yupGitHub stars✅✅✅✅string()
joiGitHub stars✅✅❌❌Joi.string()
ajvGitHub stars✅✅❌❌{type: "string"}
superstructGitHub stars✅✅✅❌string()
io-tsGitHub stars✅✅✅✅t.string
valibotGitHub stars✅✅✅✅string()
typeboxGitHub stars✅✅✅✅Type.String()
typiaGitHub stars✅✅✅✅typia.createAssert<string>()
ow[^1]GitHub stars✅✅✅✅ow.string
effectGitHub stars✅✅✅✅S.string
arktypeGitHub stars✅✅✅✅type('string')
deepkitGitHub stars✅✅❌❌typeOf<string>()
runtypesGitHub stars✅✅✅✅String

[^1]: For ow, only v0.28.2 is supported (sindresorhus/ow#248)

Custom validations are also supported:

export function assertString(data: unknown): string {
  if (typeof data !== 'string') {
    throw new Error('Expected a string, got: ' + data);
  }
  return data;
}

await validate(assertString, '123'); // {success: true, data: '123'}
await validate(assertString, 123); // {success: false, issues: [`ValidationIssue`]}

await assert(assertString, '123'); // '123'
await assert(assertString, 123); // throws `AggregateError`

Setup

Install TypeSchema with your package manager of choice:

npm npm install @decs/typeschema
Yarn yarn add @decs/typeschema
pnpm pnpm add @decs/typeschema
Deno https://deno.land/x/typeschema

API

Types

  • Schema

    Generic interface for schemas
    An union of the schema types of all supported libraries

  • TypeSchema<TOutput, TInput = TOutput>

    Interface for a wrapped schema, exposing all its operations

  • Infer<TSchema extends Schema>

    Extracts the output type of a schema

  • InferIn<TSchema extends Schema>

    Extracts the input type of a schema

  • ValidationIssue

    Generic interface for validation issues
    Includes a message and an optional path

Functions

  • wrap(schema)

    wrap<TSchema extends Schema>(
      schema: TSchema,
    ): TypeSchema<Infer<TSchema>, InferIn<TSchema>>
    

    Returns the wrapped schema with access to all its operations

  • validate(schema, data)

    validate<TSchema extends Schema>(
      schema: TSchema,
      data: unknown,
    ): Promise<ValidationResult<Infer<TSchema>>>
    

    Returns the validated data or a list of ValidationIssues

  • assert(schema, data)

    assert<TSchema extends Schema>(
      schema: TSchema,
      data: unknown,
    ): Promise<Infer<TSchema>>
    

    Returns the validated data or throws an AggregateError

Acknowledgements

版本与发布记录

@decs/typeschema 共发布 42 个版本,首次发布于 2023/07/02;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.12.2latest2024/01/212 年前
0.12.12023/10/143 年前
0.12.02023/10/053 年前
0.11.72023/09/233 年前
0.11.52023/09/233 年前
0.11.32023/09/233 年前

关于 @decs/typeschema 的常见问题

@decs/typeschema 是什么?

Universal adapter for schema validation注意:该包已被作者标记为弃用——TypeSchema has been restructured. Install @typeschema/main or @typeschema/all instead.

如何安装 @decs/typeschema?

在项目目录运行 npm install @decs/typeschema,或使用 pnpm add / yarn add / bun add。

@decs/typeschema 支持 TypeScript 吗?

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

@decs/typeschema 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@decs/typeschema 可以商用吗?

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

@decs/typeschema 的下载量有多少?

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

@decs/typeschema 还在维护吗?

最新版本 0.12.2 发布于 2024/01/21(2 年前);至今共发布 42 个版本,其中过去 12 个月发布了 0 个;首次发布于 2023/07/02。作者已将其标记为弃用,新项目建议寻找替代方案。