omar-dulaimi / prisma-zod-generator

Prisma 2+ generator to emit Zod schemas from your Prisma schema
MIT License
513 stars 45 forks source link

Drop the explicit types and let the ts infer types #45

Closed Nikola-Milovic closed 1 year ago

Nikola-Milovic commented 1 year ago

Problem

When using this library (as an alternative to zod-prisma), I want to get the zod schemas of my database models and to achieve that I use the CreateInputs but the issue is that currently we lose some of the abilities of the type inference when we explicitly set the type.

Eg

import { z } from 'zod';

import type { Prisma } from '@prisma/client';

const Schema: z.ZodType<Prisma.UserSettingsCreateInput> = z
  .object({
    deactivated: z.boolean(),
    language: z.string(),
  })
  .strict();

export const UserSettingsCreateInputObjectSchema = Schema;

As stated in the docs for generic functions (but it applies here as well) when using z.ZodType<T>, this is the toplevel type that all zod types inherit from, meaning we lose the individual functions of the types. For example you cannot extend or merge on an z.object

Suggested solution

If we just drop the explicit z.ZodType<T> the typescript will infer it correctly for us and all of the functionality for the specific zod type will be available. N

import { z } from 'zod';

const Schema = z
  .object({
    deactivated: z.boolean(),
    language: z.string(),
  })
  .strict();

export const UserSettingsCreateInputObjectSchema = Schema;

Not sure if this would break something else but it seems redundant to specify the type here instead of letting the TS infer it

omar-dulaimi commented 1 year ago

Sadly, that would cause another problem:

image

So, unless we find a solution for that issue as well, I'm afraid I can't merge this PR. Have you tried the schemas in a project? like trpc for example.

Nikola-Milovic commented 1 year ago

Yeah I feared something like this will happen, should've just made this a draft instead. I'll need to explore the project a bit more and see an alternative solution, thanks for trying it out