Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with ZodSchema when using template literal types (e.g., p${string}) #3915

Open
MineYuanlu opened this issue Dec 18, 2024 · 0 comments
Open

Comments

@MineYuanlu
Copy link

I am trying to define a Zod schema for a type based on a template literal (e.g., p${string}) and use it in a generateJsonSchema function, but I am running into a TypeScript type error.

Here is the example code I am working with:

import zodToJsonSchema from 'zod-to-json-schema';

type pStr = `p${string}`;

function generateJsonSchema<T>(t: z.ZodSchema<T>) { return zodToJsonSchema(t) }

generateJsonSchema<pStr>(z.string().refine((v): v is pStr => v.startsWith('p').describe('project ID')));

This results in the following TypeScript error:

Type 'ZodEffects<ZodString, `p${string}`, string>' is not assignable to type 'ZodType<`p${string}`, ZodTypeDef, `p${string}`>'.
  Property '_input' is incompatible.
    Type 'string' is not assignable to type '`p${string}`'. ts(2345)

Issue:

I am trying to define a refined Zod schema for a type like pStr (which is a template literal type p${string}). However, TypeScript complains about the incompatibility between string and the template literal type when trying to pass the schema to the generateJsonSchema function.

I would like to know:

  • Is there a way to work around this issue while still using template literal types in Zod schemas?
  • Is there a way to generate a JSON schema for a refined type like pStr?

The goal is to provide a type (like pStr) and have Zod output the corresponding JSON schema, either manually or automatically, without running into this TypeScript compatibility error.

Environment:

  • Zod version: 3.24.1
  • TypeScript version: 5.0.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant