2.0.3 • Published 1 year ago

zod-safe v2.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

zod-safe

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
2.0.3

1 year ago

2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago