Skip to content
Discussion options

You must be logged in to vote

Also a valid solution, probably marginally more performant.

Unless you want to use z.toJSONSchema, then none of our solutions work -- mine gets rejected because it uses transform, yours results in a simple { "type": "string" } json schema.

If you or anyone else wants to do this and not lose the ability to convert to json schema, this seems to work:

const schema = z.union([
  z.literal("a"),
  z.literal("b"),
  z.string() as z.ZodType<string & {}>,
]);
type Schema = z.infer<typeof schema>;
// type Schema = "a" | "b" | (string & {})

Resulting schema is { "anyOf": [{ "type": "string", "const": "a" }, { "type": "string", "const": "b" }, { "type": "string" }] }.

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@chenxin-yan
Comment options

@rijenkii
Comment options

Answer selected by chenxin-yan
@chenxin-yan
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants