Skip to content

sorgloomer/zod-safe

Repository files navigation

zod-safe

Test License

GitHub   •   npm   •   Issues   •   @hege_hegedus

Helper types to make sure a zod schema exactly matches a given interface.

Particularly useful when the types are defined in another package, managed by someone else or generated by some tool, and the source does not provide a way to parse/validate objects against the type.

Example usage

Install

npm i --save zod-safe

Check a zod schema in an expression

import { Exactly, ZodSafe } from 'zod-safe';
import * as z from 'zod';

export interface ContactDto {
  id: number;
  name?: string;
}

export const ContactSchema = ZodSafe(
  z.object({
    id: z.number().int(),
    name: z.string(),
    // Oops, we forgot optional!
  })
).infer<Exactly<ContactDto>>();
//      ^^^^^^^^^^^^^^^^^^^
//  The types of 'get().name' are incompatible between these types.
//  Type 'string | undefined' is not assignable to type 'string'.

Or validate the schema in a separate statement

ZodSafe(ContactSchema).infer<Exactly<ContactDto>>();
//                           ^^^^^^^^^^^^^^^^^^^

Fine-grained type assertion example

import { Extends, Super, ZodSafe } from 'zod-safe';
import * as z from 'zod';

export interface TransferDto {
  amount: string;
  description?: string;
}

export interface TransferEntity {
  amount?: bigint;
  description?: string;
}

export const TransferSchema = z.object({
  amount: z.string().transform(BigInt).optional(),
  description: z.string().optional(),
});

ZodSafe(TransferSchema).matches<{
  input: Super<TransferDto>,
  output: Extends<TransferEntity>,
}>();

Similar projects

  • tsafe : also allows for checking strict type equality for zod, but does not produce nice error messages

About

Typecheck Zod schemas to match a given type

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published