Save Zod schema programmatically to a file #3356
-
Is there a way to programmatically save a zod schema to a file? Simple exampe: import { z } from "zod";
import fs from "fs";
const schema = z.object({ foo: z.coerce.string() });
fs.writeFileSync("foo.js", `const schema = ${JSON.stringify(schema)}`); Outputs: const schema = {"_def":{"unknownKeys":"strip","catchall":{"_def":{"typeName":"ZodNever"}},"typeName":"ZodObject"},"_cached":null} But i need: const schema = z.object({ foo: z.coerce.string() }) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
if you want to write the actual code into the file, you can utilize Using AST Viewer you can get the exact code samples required for that purpose. // const schema = z.object({ foo: z.coerce.string() })
factory.createVariableStatement(
undefined,
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(
factory.createIdentifier("schema"),
undefined,
undefined,
factory.createCallExpression(
factory.createPropertyAccessExpression(
factory.createIdentifier("z"),
factory.createIdentifier("object")
),
undefined,
[factory.createObjectLiteralExpression(
[factory.createPropertyAssignment(
factory.createIdentifier("foo"),
factory.createCallExpression(
factory.createPropertyAccessExpression(
factory.createPropertyAccessExpression(
factory.createIdentifier("z"),
factory.createIdentifier("coerce")
),
factory.createIdentifier("string")
),
undefined,
[]
)
)],
false
)]
)
)],
ts.NodeFlags.Const | ts.NodeFlags.Constant | ts.NodeFlags.Constant
)
); Then you can print that code into a file — find an example implementation in |
Beta Was this translation helpful? Give feedback.
-
@RobinTail @timheerwagen i have the same issue, but when using ZodToTs it only gives me the type output, not the actual zod definition. |
Beta Was this translation helpful? Give feedback.
if you want to write the actual code into the file, you can utilize
factory
fromtypescript
.Using AST Viewer you can get the exact code samples required for that purpose.