question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

z.ZodType and z.ZodSchema do not seem to work as I expect

See original GitHub issue

Hi there!

I’ve discovered the lib recently and have a question that is probably silly.

I have an application that defines its domain with Typescript, which I want to be the single source of truth. This means I’m not interested in inferring static types from Zod, but the other way around. I want Zod to obey what Typescript dictates and want the TS compiler to let me know when any inconsistency arises. I assume the dual definition of types and parsers.

I’ve tried to achieve this with z.ZodType<MyType> and z.ZodSchema<MyType> with no success and I have not found a clue to follow from the readme of the project, which seems to be the only documentation available.

I’ve prepared a small dumb example that I hope will help you understand what I intend to do (CodeSandbox here):

import * as z from "zod";

type A = {
  foo: string;
  bar: string;
};

// This parser exactly matches interface A so we have no errors. So far so cool.
const AParser: z.ZodType<A> = z.object({
  foo: z.string(),
  bar: z.string()
});

///////////////////////////////////////////////////////////////

type B = {
  bar: string;
};

// Why I get no errors on a parser that does not match the type z.ZodType<B>?
const BParser: z.ZodType<B> = z.object({
  foo: z.string(),
  bar: z.string()
});

I have some experience with io-ts. Please find here a CodeSandbox demonstrating the result I’d expect.

Thx!!

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:2
  • Comments:5

github_iconTop GitHub Comments

3reactions
amonsosanzcommented, Dec 17, 2021

Just for reference and in case it’s useful for someone else facing these problems, we’ve ended up applying this solution, which works quite well for us since the compiler warns us whenever there’s an inconsistency between the TS types and the Zod parsers.

type Exact<T, U> = [T, U] extends [U, T] ? true : false;

const StrictSchema: <T>() => <U>(
  u: Exact<ZodSchema<T>, ZodSchema<U>> extends true
    ? Exact<Required<T>, Required<U>> extends true
      ? ZodSchema<U>
      : never
    : never
) => ZodSchema<T> =
  () =>
  <T>(u: unknown) =>
    u as ZodSchema<T>;
  • The helper type Exact returns true whenever the 2 generic types match and false otherwise.
  • The helper function StrictSchema accepts a generic type and returns a function that expects a ZodSchema as param.

I’ve updated the CodeSandbox to demonstrate how it works (from line 38) and it seems to work in all the cases:

  • Omit in a ZodSchema an optional prop of the TS type.
  • Forget to make optional in a ZodSchema and optional prop of the TS type.
  • Omit in a ZodSchema a required prop of the TS type.
  • Make optional in a ZodSchema a required prop of the TS type.
  • Add to a ZodSchema a prop that does not exist in the TS type.

Credits should go to @yuhr, who put us on the right track.

0reactions
stale[bot]commented, Mar 2, 2022

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Typecheck schemas against existing types · Issue #372
TL;DR I would love to have a way to ensure that a Zod schema matches an existing type definition using the normal Typescript...
Read more >
TypeScript schema validation with Zod - Iskander Samatov
Schema validation will help you ensure that your data is valid during runtime and Zod is the one of the best TypeScript libraries...
Read more >
Error when trying to build Fastify-Zod validation schema
Models.d.ts(2, 59): The expected type comes from property 'createUserSchema' which is declared here on type 'Models'. Using zod@3.18.0 and ...
Read more >
Data validation with automatic typing using zod
So that we don't have to maintain both types and code for validation at the same time. To solve this problem, we can...
Read more >
Schema validation in TypeScript with Zod
This is where it's better to use objects in Zod. You can create a schema for a set of properties you want at...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found