rroumenov/zod-to-x(opens in a new tab)
Language: TypeScript
Multi language types generation from Zod schemas.
- stars
- 4
- watchers
- 1
- forks
- 0
- open issues
- 0
- Last updated
- 07/27/2026
Language: TypeScript
Multi language types generation from Zod schemas.

Image generated using Canvas AI.
@zod-to-x is a Zod-based library designed to establish a centralized methodology for defining data structures. It allows you to transpile these definitions into various programming languages in a clear and straightforward way. This tool addresses a fundamental requirement of any software: having a clear understanding of the data it handles.
Important Announcement: zod-to-x@2.0.0 has been released, introducing migration to Zod V4. At this stage, only the existent behavior has been migrated, while new features like Literal Templates are still under analysis. Only the complete Zod V4 version will be supported, not v4-mini. Additionally, zod-to-x@1.X.Y will continue to be maintained for Zod V3, and any new transpilation languages will also be supported in version 1.
@zod-to-x?@zod-to-x?Managing data consistency across multiple layers and languages is a common challenge in modern software development. @zod-to-x solves this by allowing you to define your data models once and effortlessly transpile them into multiple programming languages. Here’s why it stands out:
Centralized Data Definition
Define your data structures in one place using the powerful @zod library. This eliminates redundancy, reduces inconsistencies, and simplifies maintenance across your entire codebase, all while allowing you to continue leveraging any npm package in the @zod ecosystem.
Multi-Language Compatibility
Generate data models for TypeScript, Python (Pydantic), C++, Go, and Protobuf V3. No more manually rewriting models for different platforms.
Enhanced Productivity
Automate the transpilation of data models to save time, reduce errors, and let your team focus on business logic instead of boilerplate code.
npm install zod-to-x zod
(*) zod@3.25.28 version or greather is required.
extendZod method after the first @zod import:import { z } from "zod/v4"; import { extendZod } from "zod-to-x"; extendZod(z);
This extension appends a zod2x method to:
import { z } from "zod/v4"; import { extendZod, Zod2Ast, Zod2XTranspilers } from "zod-to-x"; extendZod(z); // The extend step can be skipped if it has already been done. /** * 1) Define a data model using Zod schemas */ const VisitorSchema = z.object({ id: z.uuid(), name: z.string(), email: z.email(), visitDate: z.date(), comments: z.string().optional(), }).zod2x("Visitor"); // Add your expected output type name using the 'zod2x' method. /** * 2) Build an AST node of the Zod schema */ const visitorNodes = new Zod2Ast().build(VisitorSchema); /** * 3) Generate types in the desired language. * Depending on the transpiled language, data models can be generated using classes. */ const tsVisitorAsInterface: string = new Zod2XTranspilers.Zod2Ts().transpile(visitorNodes); console.log(tsVisitorAsInterface) // output: // export interface Visitor { // id: string; // name: string; // email: string; // visitDate: Date; // comments?: string; // } const tsVisitorAsClass: string = new Zod2XTranspilers.Zod2Ts({outType: "class"}).transpile(visitorNodes); console.log(tsVisitorAsClass) // output: // export class Visitor { // id: string; // name: string; // email: string; // visitDate: Date; // comments?: string; // constructor(data: Visitor) { // this.id = data.id; // this.name = data.name; // this.email = data.email; // this.visitDate = data.visitdate; // this.comments = data.comments; // } // }
Starting from v1.3.0, a best practices helper is enabled by default when handling data intersections and unions:
These rules help ensure that each data model follows the single responsibility principle. Otherwise, an error will be thrown when building an ASTNode.
NOTE: You can disable these rules at your own risk by setting the strict flag to false when building the ASTNode data model. However, any unexpected behavior or issues resulting from this will not be supported.
const DataA = z.object({ keyA: z.string(), keyC: z.string() }).zod2x("DataA"); const DataB = z.object({ keyB: z.string(), keyC: z.number() }).zod2x("DataB"); const Intersection = z.intersection(DataA, DataB).zod2x("Intersection"); // C++ case (with inheritance) // struct Intersection : public DataA, public DataB { // // Intersection fields are inherited from base structs. // }; // Typescript case (with attribute merging) // class Intersection { // keyA: string; // keyB: string; // keyC: number; // Shared key overriden using the last type. // };
const DataA = z.object({ keyA: z.string(), keyD: z.string() }).zod2x("DataA"); const DataB = z.object({ keyB: z.string(), keyD: z.string() }).zod2x("DataB"); const Intersection = z.intersection(DataA, DataB).zod2x("Intersection"); // C++ case (with variant type) // using Intersection = std::variant<DataA, DataB>; // Typescript case (with attributes merge) // class Intersection { // keyA?: string; // Different keys are set as optional // keyB?: string; // keyD: number; // Shared key preserved as is. // };
To enhance data modeling and the serialization/deserialization of a discriminated union type, two key steps should be considered:
ZodEnum the define the discriminator key options.ZodLiteral to define the specific value of the discriminator key.Example of discriminant definition:
// Define message types export const MsgType = z.enum(["TypeA", "TypeB"]).zod2x("MsgType"); // Define different message structures based on the 'msgType' value. const MessageA = z .object({ key: z.string(), // Assign the type using the corresponding MsgType value and link it with 'zod2x'. msgType: z.literal(MsgType.Values.TypeA).zod2x(MsgType), }) .zod2x("MessageA"); const MessageB = z .object({ otherKey: z.string(), // Same process as MessageA. msgType: z.literal(MsgType.Values.TypeB).zod2x(MsgType), }) .zod2x("MessageB"); // Define the main Message type using ZodDiscriminatedUnion. export const Message = z .discriminatedUnion("msgType", [MessageA, MessageB]) .zod2x("Message");
Example of C++ output:
// Discriminated union with direct serialization/deserialization inline void from_json(const json& j, Message& x) { const auto& k = j.at("msgType").get<std::string>(); if (k == "TypeA") { x = j.get<MessageA>(); } else if (k == "TypeB") { x = j.get<MessageB>(); } else { throw std::runtime_error("Failed to deserialize Message: unknown format"); } } // Using a regular union or a discriminated union without the above approach: // Fallback to try-catch for serialization/deserialization inline void from_json(const json& j, Message& x) { try { x = j.get<MessageA>(); return; } catch (const std::exception&) { } try { x = j.get<MessageB>(); return; } catch (const std::exception&) { throw std::runtime_error("Failed to deserialize Message: unknown format"); } }
To improve Separation of Concerns (SoC), the Dependency Rule, and Maintainability, a new layer-based modeling approach was introduced in v1.4.0. This approach establishes relationships between models in separate files, which are transpiled into file imports. This feature provides a powerful tool not only for type systems with robust architectures, such as Clean, Hexagonal, or Layered, but also enforces their usage.
To achieve this, new components are included:
transpile() method that receives the target language class.true.v1.4.6, primitive data types and arrays are also transpiled when using Layered modeling if they are declared as property inside the layer class. They are output as aliases of the types they represent. Setting it to false will disable this behavior (except for arrays, which are always transpiled). Default is true.v2.0.0, a global interface was transpiled with all layer properties. With externalInheritance and basicType, this behavior has started to become obsolete, so it is not included by default. If needed, set to false.@Domain({ namespace: "USER", file: "user.entity" }) class UserModels extends Zod2XModel { userRole = z.enum(["Admin", "User"]).zod2x("UserRole"); // (*) userEmail = z.email(); // This will be transpiled as an alias. userEntity = z.object({ id: z.uuid(), name: z.string().min(1), email: this.userEmail, age: z.int().nonnegative().optional(), role: this.userRole, }); // (*) } const userModels = new UserModels(); console.log(userModels.transpile(Zod2XTranspilers.Zod2Ts)); // Output: // export enum UserRole { // Admin = "Admin", // User = "User", // } // export type UserEmail = string; // export interface UserEntity { // id: string; // name: string; // email: UserEmail; // age?: number; // role: UserRole; // }
(*) Thanks to the Layer decorator, the use of zod2x for type naming can now be omitted, simplifying and clarifying the process of model definition. By default, it will take the property name and apply a Pascal case convention (example: myProperty -> MyProperty).
You can still use it if you want to enforce a different type name.
// Create DTOs using previously defined user models. @Application({ namespace: "USER_DTOS", file: "user.dtos" }) class UserDtos extends Zod2XModel { createUserUseCaseDto = userModels.userEntity.omit({ id: true }); // (*) createUserUseCaseResultDto = userModels.userEntity .omit({ role: true }) .extend({ createdAt: z.date(), updatedAt: z.date(), }); // (*) } const userDtos = new UserDtos(); console.log(userDtos.transpile(Zod2XTranspilers.Zod2Ts)) // Output: // import * as USER from "./user.entity"; <--- Reusing models from other layers. // export interface CreateUserUseCaseDto { // name: string; // email: USER.UserEmail; // age?: number; // role: USER.UserRole; // } // export interface CreateUserUseCaseResultDto { // id: string; // name: string; // email: USER.UserEmail; // age?: number; // createdAt: Date; // updatedAt: Date; // }
(*) Any modification of an existing model (in this case, userEntity) will lose the relation with that model, but not its children. In the case of the CreateUserUseCaseDto type, the role field will remain linked to the existing one in the user.entity file.
3 - Are your models too large? Simplify them!
If you are dealing with complex models whose definitions are too extensive, split them into multiple classes and then combine them using Zod2XMixin as shown below:
import { Zod2XMixin } from "zod-to-x"; // Sub-models do not require a layer decorator; it is applied automatically when inherited by the main model. // Sub-model 1 class CreateUserUseCaseDto { createUserUseCaseDto = userModels.userEntity.omit({ id: true }); } // Sub-model 2 class CreateUserUseCaseResultDto { createUserUseCaseResultDto = userModels.userEntity .omit({ role: true }) .extend({ createdAt: z.date(), updatedAt: z.date(), }); } // Main model @Application({ namespace: "USER_DTOS", file: "user.dtos" }) class UserDtos extends Zod2XMixin( [CreateUserUseCaseDto, CreateUserUseCaseResultDto], // Inherit the desired sub-models. Zod2XModel // Zod2XModel must still be the base class. ) {} export const userDtos = new UserDtos(); console.log(userDtos.transpile(Zod2XTranspilers.Zod2Ts)) // Output (same as above): // import * as USER from "./user.entity"; <--- Reusing models from other layers. // export interface CreateUserUseCaseDto { // name: string; // email: string; // age?: number; // role: USER.UserRole; // } // export interface CreateUserUseCaseResultDto { // id: string; // name: string; // email: string; // age?: number; // createdAt: Date; // updatedAt: Date; // }
4 - Difference of using externalInheritance (defaults) or not.
// Default output (externalInheritance = true) @Application({ namespace: "USER_DTOS", file: "user.dtos" }) class UserDtos extends Zod2XModel { createUserUseCaseDto = userModels.userEntity.omit({ id: true }); createUserUseCaseResultDto = userModels.userEntity; } // Output: // import * as USER from "./user.entity"; // export interface CreateUserUseCaseDto { // name: string; // email: string; // age?: number; // role: USER.UserRole; // } // export interface CreateUserUseCaseResultDto extends USER.UserEntity {} // --------------- // If `USER.UserEntity` were a Union or a Discriminated Union, the output would be a Type equivalent to `USER.UserEntity` rather than an Interface that extends it.
// Output without externalInheritance @Application({ namespace: "USER_DTOS", file: "user.dtos", externalInheritance: false, skipLayerInterface: false}) class UserDtos extends Zod2XModel { createUserUseCaseDto = userModels.userEntity.omit({ id: true }); createUserUseCaseResultDto = userModels.userEntity; } // Output: // import * as USER from "./user.entity"; // export interface CreateUserUseCaseDto { // name: string; // email: string; // age?: number; // role: USER.UserRole; // } // export interface UserDtos { // createUserUseCaseDto: CreateUserUseCaseDto; // createUserUseCaseResultDto: USER.UserEntity; // } // --------------- // In this case, the type of `createUserUseCaseResultDto` is inferred from the parent model (`UserDtos`, only if skipLayerInterface = false), but there is no explicit definition of the type itself.
If the provided layer decorators do not meet your requirements, you can easily define custom ones:
import { Layer, IZod2xLayerMetadata, Zod2XModel } from "zod-to-x"; // Create an enumerate with layer indexes enum MyLayers { MyDomainLayer = 0, MyApplicationLayer = 1, MyInfrastructureLayer = 2, // ... } // Create custom layer decorators function MyDomainLayer(opt: Omit<IZod2xLayerMetadata, "index">) { return Layer({ ...opt, index: MyLayers.MyDomainLayer }); } // ... // Use the custom decorators @MyDomainLayer({file: "...", namespace: "..."}) class MyEntityModels extends Zod2XModel { // ... }
Since v1.5.0, basic generic types can be generated using layered modeling. A few key points should be kept in mind when working with them:
ZodObject properties. The new createGenericType method should be used to indicate the generic property.@Infrastructure({ namespace: "GENERICS_INFRA", file: "layered_generics.infra", }) class GenericsInfrastructure extends Zod2XModel { readonly HttpSuccessfulResponse = z.object({ success: z.literal(true), data: createGenericType("T"), }); readonly HttpUnsuccessfulResponse = z.object({ success: z.literal(false), message: z.string(), details: z.record(z.any()).optional(), }); } // Output: // export interface HttpSuccessfulResponse<T> { // success: true; // data: T; // } // // export interface HttpUnsuccessfulResponse { // success: false; // message: string; // details?: Record<string, any>; // }
useGenericType method should be used to indicate the parent generic type and the value that the generic will take, which should be a previously defined type.// inside GenericsInfrastructure class readonly SomeDtoResult = z.object({ id: z.string(), name: z.string(), age: z.number().int().nonnegative(), }); readonly ResponseItem = useGenericType(this.HttpSuccessfulResponse, { data: this.SomeDtoResult, // Indicate the generic property and the value it takes // ... other generic properties, if exist. }); // Output: // export interface SomeDtoResult { // id: string; // name: string; // age: number; // } // // export interface ResponseItem extends HttpSuccessfulResponse<SomeDtoResult> {}
z.lazy() operator. This is required to ensure metadata existence. It is applied to the used type, except when dealing with ZodIntersect, ZodUnion or ZodDiscriminatedUnion, where it should be applied to these methods instead of the type. Additionally, they support only inline generics usage:// inside GenericsInfrastructure class readonly ObjectWithGeneric = z.object({ // Property with reference to a generic based type: requires lazy operator directGenericUse: z.lazy(() => this.ResponseItem), // Property with inline generic usage: `useGenericType` is lazy by default indirectGenericUse: useGenericType(this.HttpSuccessfulResponse, { data: this.SomeDtoResult }), }); // Case of ZodUnion, ZodDiscriminatedUnion or ZodIntersection. readonly DiscriminantDataRetrieve = z.lazy(() => // Lazy the zod type itself z.discriminatedUnion( "success", [ // Inline generic usage useGenericType( this.HttpSuccessfulResponse, { data: this.SomeDtoResult }, true // Disable default lazy wrapper ), // Non generic types: normal references this.HttpUnsuccessfulResponse, ] ) ); // Output // export interface ObjectWithGeneric { // directGenericUse: ResponseItem; // indirectGenericUse: HttpSuccessfulResponse<SomeDtoResult>; // } // // export type DiscriminantDataRetrieve = // | HttpSuccessfulResponse<SomeDtoResult> // | HttpUnsuccessfulResponse;
Complete definition examples can be found here.
Common options:
true.true.interface.false.Pydantic is used for data validation and serialization/deserialization. Generates Pydantic BaseModel classes with full type hints.
false.Nlohmann dependency is used for data serialization/deserialization. For C++11, Boost dependency is used. For C++17 or newer, standard libraries are used.
null. Defaults to false.struct.false.false.Generates idiomatic Go structs with encoding/json struct tags. Requires Go 1.18+ for generic type support.
"models".false.json:"fieldName" struct tags. Defaults to true.json_annotation + json_serializable are used for JSON serialization/deserialization. The .g.dart part file is generated externally by dart run build_runner build.
false.@JsonSerializable(), @JsonEnum, @JsonKey annotations and fromJson/toJson stubs. Requires package:json_annotation.part '${partFile}.g.dart' directive. Automatically set when using layered modeling. If omitted, no part directive is emitted.Additional useful tools to convert Zod Schemas into different formats.
In case of use of Google protobuf to improve communication performance, you can automatically generate proto files directly from your models. Check out this input example and its output
Options:
true.false.false.Limitations:
import { z } from "zod/v4"; import { extendZod, Zod2XConverters } from 'zod-to-x'; extendZod(z); // Example using model from `Quick-start` section const visitorProtobuf = Zod2XConverters.zod2ProtoV3(VisitorSchema); console.log(visitorProtobuf); // Proto file of Visitor's model // Example using model from `Layer modeling` section const createUserDtoProtobuf = Zod2XConverters.zod2ProtoV3(userDtos.createUserUseCaseDto); console.log(createUserDtoProtobuf); // Proto file of CreateUserUseCaseDto's model
For a detailed mapping of supported Zod types across supported targets, please refer to the SUPPORTED_ZOD_TYPES.md file.
Choose the approach that best suits your needs, either Layered or non-Layered modeling, and avoid mixing them whenever possible, especially when working with enumerations, objects, unions, or intersections (except for ZodLiteral.zod2x(), which simply links a literal value to the enumeration it belongs to, if applicable). Their metadata handling differs slightly, which may result in some types not being transpiled as expected.
In Layered modeling, the transpilation of primitive types can be completely disabled or combined by defining them outside the layer class:
// External primitive const stringUUID = z.uuid(); @Domain({ namespace: "USER", file: "user.entity" }) class UserModels extends Zod2XModel { // Internal primitive userEmail = z.email(); // This will be transpiled as an alias. It is a layer property. userEntity = z.object({ id: stringUUID, // "stringUUID" will not be transpiled as an alias. It is not a layer property. email: this.userEmail, }); } export const userModels = new UserModels();
ZodLazy shall be used:// Consider the previous UserModels import { z } from "zod/v4"; @Application({ namespace: "USER_DTOS", file: "user.dtos", externalInheritance: false}) class UserDtos extends Zod2XModel { // OK - Type declaration. It creates a new type based on userEntity but without ID. createUserUseCaseDto = userModels.userEntity.omit({ id: true }); // OK - Redeclaration of external type. Could be useful for typing coherence. // "createUserUseCaseResultDto" becomes an alias of "userModels.userEntity". createUserUseCaseResultDto = userModels.userEntity; // OK - Redeclaration of an internal type. Could be useful for typing coherence. // "createUserUseCaseDtoV2" becomes an alias of "createUserUseCaseDto". createUserUseCaseDtoV2 = this.createUserUseCaseDto; // NOK - Redeclaration of an alias. It will be an alias of "userModels.userEntity" // because "createUserUseCaseResultDto" is aliased during runtime. createUserUseCaseResultDtoV2 = this.createUserUseCaseResultDto; // OK, but avoid it - Redeclaration of an alias. It will wait until // "createUserUseCaseResultDto" is aliased and then will become an alias // of "createUserUseCaseResultDto" createUserUseCaseResultDtoV3 = z.lazy(() => this.createUserUseCaseResultDto), }