npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@duplojs/zod-to-typescript

v0.2.2

Published

<a name="top"></a>

Downloads

169

Readme

@duplojs/zod-to-typescript is a library that converts Zod schemas to TypeScript types.

Installation

To consume @duplojs/zod-to-typescript, you need to install the npm package and zod.

npm install @duplojs/zod-to-typescript zod

Usage

1. Import necessary modules

import { z as zod } from 'zod';
import { ZodToTypescript } from '@duplojs/zod-to-typescript';

2. Define Zod schema

Create a Zod schema that you want to convert to TypeScript:

const schema = zod.object({
  name: zod.string(),
  age: zod.number(),
  isStudent: zod.boolean(),
});

3. Convert Zod schema to TypeScript type

Use the convert method of ZodToTypescript to convert the Zod schema to a TypeScript type declaration:

const options: ConvertOptions = {
    name: "User", // Optional: Specify a name for the TypeScript type
    export: true, // Optional: Export the TypeScript type
};

const tsType = ZodToTypescript.convert(userSchema, options);

4. Output the TypeScript type

The convert method returns a string containing the TypeScript type declaration. You can output this string to a file or use it directly in your code:

console.log(tsType);
// output:
export type User = {
  name: string;
  age: number;
  isStudent: boolean;
};

5. Full Example

import { z as zod } from 'zod';
import { ZodToTypescript } from '@duplojs/zod-to-typescript';

const schema = zod.object({
  name: zod.string(),
  age: zod.number(),
  isStudent: zod.boolean(),
});

const options: ConvertOptions = {
    name: "User",
    export: true,
};

const tsType = ZodToTypescript.convert(schema, options);

console.log(tsType);
// Output: 
export type User = { 
    name: string; 
    age: number; 
    isStudent: boolean; 
};

6. Using Identifiers

Identifiers allow you to give a name to a schema. You can also use a schema directly as an identifier. This can be useful when you have nested schemas and want to refer to them by name.

import { ZodToTypescript, ConvertOptions } from "@duplojs/zod-to-typescript";
import { z as zod } from "zod";

// Define your schemas
const addressSchema = zod.object({
    street: zod.string(),
    city: zod.string(),
    zipCode: zod.string(),
});

const companySchema = zod.object({
    name: zod.string(),
    address: addressSchema,
}).identifier("Company"); // automatically identifies the schema as "Company"

const employeeSchema = zod.object({
    employeeId: zod.number(),
    name: zod.string(),
    position: zod.string(),
    company: companySchema,
})

// Convert the Employee schema to TypeScript
const options: ConvertOptions = {
    name: "Employee",
    indentifiers: [
        {
            name: "Address", // define manually
            zodSchema: addressSchema,
        },
    ],
    export: true,
};

const tsType = ZodToTypescript.convert(employeeSchema, options);

console.log(tsType);
// Output:
export type Address = {
    street: string;
    city: string;
    zipCode: string;
};

export type Company = {
    name: string;
    address: Address;
};

export type Employee = {
    employeeId: number;
    name: string;
    position: string;
    company: Company;
};

7. Recursive Schemas

Recursive schemas allow you to define schemas that reference themselves. This is useful for defining structures like trees or linked lists. You can use zod.lazy() to create recursive schemas.

import { ZodToTypescript, ConvertOptions } from "@duplojs/zod-to-typescript";
import { z as zod } from "zod";

const categorySchema = zod.object({
    name: zod.string(),
    subcategories: zod.lazy(() => categorySchema.array()),
}).identifier("Category");

const tsType = ZodToTypescript.convert(categorySchema, { export: true });

console.log(tsType);
// Output:
export type Category = {
    name: string;
    subcategories: Category[];
};

8. New instance

You can create instance of ZodToTypescript to make an environment types.

import { ZodToTypescript } from "@duplojs/zod-to-typescript";
import { z as zod } from "zod";

const commentSchema = zod.object({
    user: zod.lazy<any>(() => userSchema),
    content: zod.string(),
}).identifier("Comment");

const postSchema = zod.object({
    title: zod.string(),
    content: zod.string(),
    date: zod.coerce.date(),
    comments: commentSchema.array(),
});

const userSchema = zod.object({
    userId: zod.number(),
    firstname: zod.string(),
    lastname: zod.string(),
    posts: postSchema.array(),
});

const ztt = new ZodToTypescript();

ztt.append(commentSchema);
ztt.append(userSchema, "User");
ztt.append(postSchema, "Post");

const tsType = ztt.toString()

console.log(tsType);
// Output:
type Comment = {
    user: User;
    content: string;
};

type User = {
    userId: number;
    firstname: string;
    lastname: string;
    posts: Post[];
};

type Post = {
    title: string;
    content: string;
    date: Date;
    comments: Comment[];
};

9. Hooks

Converting a Zod schema to TypeScript requires making choices. Should we generate the type based on the schema's output or the type expected by the schema? Zod-to-Typescript has made these choices, but it doesn't impose them on you. Thanks to the hooks, you can choose your use cases.

import { ZodToTypescript } from "@duplojs/zod-to-typescript";
import { z as zod } from "zod";

const zodSchema = zod.object({
    prop1: zod.date(),
    prop2: zod.number(),
});

const tsType = ZodToTypescript.convert(
    zodSchema,
    {
		name: "Schema"
        zodSchemaHooks: [
            (zodSchema, context, output) => output(
                "next",
                zodSchema instanceof ZodNumber && zodSchema._def.coerce
                    ? zod.number().optional()
                    : zodSchema,
            ),
            (zodSchema, context, output) => output(
                "stop",
                zodSchema instanceof ZodDate ? zod.string() : zodSchema,
            ),
        ],
    },
);

console.log(tsType);
// Output:
type Schema = {
    prop1: string;
    prop2?: number | undefined;
};

Hooks are functions that intercept the Zod schema before it looks for its transformer. This allows returning another schema instead. The hook must return the result of the output function. output takes a string as its first argument ("next" or "stop"), which indicates whether the hook execution should stop or continue after it. The second argument corresponds to the schema that will be interpreted.

More Examples

For more examples, please check the unit tests for each type in the tests directory. The tests provide comprehensive examples of how to use each supported type with ZodToTypescript.

Acknowledgements

I would like to thank sachinraja for creating the zod-to-ts zod package, which served as an inspiration for this project.