Schema Validation 2024
Valibot (1KB tree-shakeable), ArkType (najszybszy), TypeBox (JSON Schema), Zod v4 (nowy core) i porównanie.
6 bibliotek schema validation — bundle i kiedy
Zod v4, Valibot, ArkType, TypeBox, Yup i Superstruct — bundle size i kiedy wybrać.
| Biblioteka | Bundle | Kiedy |
|---|---|---|
| Zod v4 | ~8KB (treeshaken) | Standard — ekosystem, React, Next.js, tRPC |
| Valibot | ~1KB (per validator) | Edge functions, bundle size critical, tree-shake |
| ArkType | ~11KB | Performance-critical, TypeScript-like syntax |
| TypeBox | ~15KB | Fastify backend, JSON Schema potrzebny, OpenAPI |
| Yup | ~12KB | Legacy Formik — migruj do Zod+RHF |
| Superstruct | ~3KB | Minimalistyczny, customizable, starsze projekty |
Często zadawane pytania
Valibot — mała alternatywa dla Zod w TypeScript?
Valibot: modular schema validation. Fabian Hiller. Bundle-size first. Tree-shakeable. Instalacja: npm install valibot. Modularne importy: import {object, string, number, email, minLength, parse, safeParse} from 'valibot'. Schemat: const UserSchema = object({name: string([minLength(2)]), email: string([email()]), age: number()}). Parsowanie: const user = parse(UserSchema, input). Rzuca ValiError. safeParse: const result = safeParse(UserSchema, input). result.success ? result.output : result.issues. Bundle size: Zod v3: ~14KB (treeshake: ~8KB). Valibot: ~1KB treeshaken! Każdy validator osobno importowany. Tylko to co używasz. TypeScript: type User = InferOutput typeof UserSchema. InferInput — przed transformacją. InferOutput — po. Transformacje: transform(string(), (val) => val.trim()). coerce(number(), Number) — konwertuj typy. optional(string()) — undefined ok. nullable(string()) — null ok. Nested: object z nested object. array(string()). tuple([string(), number()]). union([literal('a'), literal('b')]). Async: parseAsync, safeParseAsync. Asynchroniczne validatory. Baza danych sprawdzenie. Errors: ValiError. issues tablica. path dla nested. message — human readable. i18n messages: setGlobalConfig({lang: 'pl'}). Własne wiadomości błędów. Pipy: pipe(string(), email(), maxLength(255)). Kompozycja walidatorów. Custom: custom((val) => val > 0, 'Must be positive'). Elastyczne. Kiedy Valibot: bundle size critical. Edge functions. Wiele schema parsowania. Zod kompatybilność: nie 100% (inne API).
ArkType — runtime type inference i fastest validator?
ArkType: TypeScript-syntax schema validation. Matt Portner. Składnia jak TypeScript. Najszybszy validator (benchmarki 2024). Instalacja: npm install arktype. Podstawy: import {type} from 'arktype'. const User = type({name: 'string', age: 'number', email: 'string.email', role: '"admin" | "user"'}). Syntax: string, number, boolean — proste typy. 'string > 0' — walidacja. '"literal"' — literal type. 'string | number' — union. 'string[]' — tablica. 'string | null' — nullable. Parsowanie: const result = User(input). result instanceof type.errors ? handleErrors() : useData(result). TypeScript: type UserType = typeof User.infer. Identyczne z definicją. Wydajność: ArkType 10-100x szybszy niż Zod dla prostych typów. JIT compilation schematu. Zod w porównaniu wolniejszy dla hot path. Zaawansowane: Morph (transform): type('string').pipe(s => s.trim()). Optional: 'string?'. Default: type({x: 'number = 0'}). Generics: type T extends type.Any. Parametryzowane schematy. narrow (refinement): .narrow((val, ctx) => { if (val < 0) return ctx.error('Must be positive') }). Date: 'Date'. instanceof: type('instanceof', MyClass). Intersection: type('string & /^[a-z]+$/') — regex. Errors: type.errors — ArkTypeError[]. message concatenated. ArkErrors.summary — czytelne. Kiedy ArkType: performance-critical parsowanie. TypeScript-like syntax preferowany. Nowe projekty. vs Zod: Zod — większy ekosystem. ArkType — szybszy, TypeScript syntax.
TypeBox — JSON Schema compatible validator?
TypeBox: Sincerity.io. JSON Schema + TypeScript types. Generuje JSON Schema. Runtime validation. Fast. Instalacja: npm install @sinclair/typebox. import {Type, Static} from '@sinclair/typebox'. Schematy: const User = Type.Object({name: Type.String({minLength: 2}), age: Type.Integer({minimum: 0}), email: Type.String({format: 'email'}), tags: Type.Array(Type.String())}). TypeScript: type User = Static typeof User. Kompiluje do JSON Schema. Walidacja: import {TypeCompiler} from '@sinclair/typebox/compiler'. const C = TypeCompiler.Compile(User). C.Check(value) — boolean. C.Errors(value) — iterator błędów. Lub Value.Check(User, input) — wolniejszy ale bez compile. JSON Schema output: Type.Object(schema) generuje { type: 'object', properties: {...}, required: [...] }. Użyj z Ajv, Fastify, etc. Fastify integracja: Fastify używa JSON Schema natively. TypeBox + Fastify = type-safe routes. schema: {body: User} — automatyczna walidacja. Swagger/OpenAPI: typebox-json-schema. Generuj dokumentację z schematu. Type.Intersect: intersection typów. Type.Union: union. Type.Literal('admin'). Type.Enum(RoleEnum). Transformer: Value.Transform(schema). from/to transformacje. Optional i Default: Type.Optional(Type.String()). Type.Default('value'). Ajv + TypeBox: ajv.validate(User, input). JSON Schema ekosystem. ajv-formats dla email, uri, etc. Gdy TypeBox: Fastify backend. JSON Schema potrzebny. OpenAPI generowanie. Nie-React środowisko. vs Zod: TypeBox — JSON Schema, Fastify. Zod — React/Next.js ekosystem.
Zod v4 — co nowego i jak migrować?
Zod v4 (2025): przepisany core. Szybszy. Mniejszy. Nowe API. Instalacja: npm install zod@4. Breaking changes: ZodError.issues (nie errors). ZodError.format() — zmieniony output. z.string().min() — wiadomości zmienione. z.object().extend() — nowy syntax. z.discriminatedUnion — ulepszone. Co nowego: zod/mini — mały bundle (jak Valibot). z.meta() — custom metadata. z.registry() — globalne rejestrowanie. z.file() — File type. z.promise() — ulepszone. z.transform() ulepszone. Superfast parsing: benchmark 5-20x szybszy niż v3. JIT compilation. Memoizacja schematu. z.infer wyniki lepsze. Zod Mini: import {z} from 'zod/mini'. Analogiczny do Valibot (tree-shakeable). z.parse vs. parse(schema, value). Małe bundle dla edge. Migracja z v3: npm install zod@4. npx zod-codemod — automatyczna migracja. Sprawdź: .errors -> .issues. Strict mode: z.strictObject() — zamiast .strict(). Superstructure: z.interface() — openapi friendly. Interoperability: Zod + Valibot: @valibot/to-json-schema. Różne narzędzia łącz. Zod -> OpenAPI: zod-to-json-schema. Zod -> GraphQL: potterlogic/nexus-zod. Zod vs Valibot vs ArkType 2024: Zod — ekosystem, familiar API. Valibot — mały bundle. ArkType — szybki, TypeScript syntax. TypeBox — JSON Schema compat. Wybierz: Zod dla większości. Valibot/ArkType dla edge/performance.
Superstruct i Yup — starsze biblioteki i kiedy nadal używać?
Superstruct: Ianstormtaylor. Małe (~3KB). Customizable. Instalacja: npm install superstruct. import {object, string, number, validate, is, assert} from 'superstruct'. const User = object({name: string(), age: number()}). validate(User, input) — [error, data]. is(input, User) — boolean. assert(input, User) — rzuć. Customization: define('email', (val) => typeof val === 'string' && val.includes('@')). Coercion: coerce(Date, string(), val => new Date(val)). Kiedy Superstruct: starsze projekty. Minimalistyczny. Brak overhead. Nie rośnie jak Zod. Yup: Jquense. API jak Joi. React/Formik ecosystem. Instalacja: npm install yup. const schema = yup.object({name: yup.string().required().min(2), age: yup.number().min(0), email: yup.string().email().required()}). schema.validate(input) — Promise. schema.validateSync(input). schema.isValid(input) — boolean. Yup + Formik: validationSchema={schema}. Starszy pattern. React Hook Form też obsługuje. Async: yup.string().test('unique', 'Email taken', async val => {return await checkEmail(val)}). Joi: Hapi ecosystem. Node.js server validation. Kompletny. Ale duży bundle (25KB). Nie TypeScript-first. Kiedy Yup: legacy Formik code. Migruj do RHF + Zod. Zod + React Hook Form = 2024 standard. Formik nadal używany ale nie polecany. Migracja Yup -> Zod: @hookform/resolvers obsługuje oba. Stopniowa migracja. Schemat per schemat. Przyszłość: Zod dominuje 2024. Valibot rośnie szybko. ArkType niszowy ale rośnie. Yup/Superstruct: maintenance mode.
Powiązane artykuły
Skontaktuj się z nami
Porozmawiajmy o Twoim projekcie. Bezpłatna wycena w ciągu 24 godzin.
Wyślij zapytanie
Telefon
+48 790 814 814
Pon-Pt: 9:00 - 18:00
adam@fotz.pl
Odpowiadamy w ciągu 24h
Adres
Plac Wolności 16
61-739 Poznań
Godziny pracy
Wolisz porozmawiać?
Zadzwoń teraz i porozmawiaj z naszym specjalistą o Twoim projekcie.
Zadzwoń teraz