🛵 TypeSchema
Unified interface for TypeScript schema validations
Many libraries rely on some sort of type validation. Their maintainers have the choice of either to:
- 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)
- Couple their code with a specific validation library: which limits adoption by developers who use another
- Support multiple validation libraries: which is a burden to keep up-to-date (tRPC picked this one)
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 providing option 3 (support multiple validation libraries) out-of-the-box.
Features
- 🚀 Decouple your code from validation libraries
- 🍃 Less than 3 kB, zero dependencies
- ✨ Easy-to-use, minimal API
Setup
Install TypeSchema with your package manager of choice:
npm | npm install @decs/typeschema |
---|
Yarn | yarn add @decs/typeschema |
---|
pnpm | pnpm add @decs/typeschema |
---|
Usage
import type {Infer, Schema} from '@decs/typeschema';
import {assert} from '@decs/typeschema';
const schema: Schema<string> = z.string();
type Type = Infer<typeof schema>;
await assert(schema, '123');
await assert(schema, 123);
API
Types
Schema<T>
Generic schemaInfer<T as Schema<unknown>>
Extracts the equivalent TypeScript type of a schema
Functions
assert<T>(schema: Schema<T>, data: unknown): Promise<T>
Returns the validated value or throws an exception
Coverage
Custom validations are also supported:
export function assertString(value: unknown): string {
if (typeof value !== 'string') {
throw new Error('Expected a string, got: ' + value);
}
return value;
}
await assert(assertString, '123');
await assert(assertString, 123);
Acknowledgement