TypeScript to Zod Schema
Convert TypeScript interfaces and type aliases to Zod validation schemas instantly. Handles unions, optional fields, arrays, enums, nested objects, and cross-references. Free, runs in your browser.
- Runs in your browser
- Tool input is not uploaded to ZeroTool servers
- Free · No Sign-Up
Scan with WeChat to share this tool
Examples, details and FAQ Worked examples, how it compares with other tools, and answers to common questions.
Supported TypeScript Features
- Basic types:
string,number,boolean,null,undefined,any,unknown,void,never,bigint,symbol - Optional properties:
prop?: type→.optional() - Union types:
A | B→z.union([A, B]) - String enums:
"a" | "b" | "c"→z.enum(["a", "b", "c"]) - Arrays:
T[]/Array<T>→z.array(T) - Nested objects: inline object types →
z.object({}) - Cross-references: named types reference each other → Schema constants
- Readonly: the
readonlymodifier is accepted and dropped; add.readonly()yourself if the inferred type should be read-only - Utility types:
Partial<T>→.partial(),Record<K, V>→z.record(K, V),Promise<T>→z.promise(T);Required<T>is passed through unchanged - Intersection types:
A & B→z.intersection(A, B) - Tuples:
[A, B]→z.tuple([A, B]) - Literal types:
"value",42,true→z.literal() extends:interface Admin extends Base→BaseSchema.extend({ ... }); a second base adds.extend(OtherSchema.shape). If a base is not an object schema (an intersection alias, for example), the result isz.intersection(BaseSchema, z.object({ ... })).- Index signatures:
[key: string]: Vnext to other properties →.catchall(V), which checks and keeps the extra keys; on its own →z.record(z.string(), V). enumdeclarations: a string enum →z.enum()of its values; numeric or mixed members (auto-numbered from 0 or from the last number) →z.union()ofz.literal()values.const enumanddeclare enumare read the same way.- Declaration order and recursion: schemas are written dependencies first, whatever the input order. A reference that closes a cycle becomes
z.lazy(() => NameSchema), and each type in the cycle is written out with an explicitz.ZodType<Name>annotation, as the Zod documentation shows for recursive types.
Example: Recursion, extends and an Index Signature
Input, with Category declared after the type that uses it:
interface Menu extends Base { root: Category; [key: string]: unknown }
interface Base { id: string }
interface Category { name: string; children: Category[] }
Output (checked with the TypeScript 5.9 compiler in strict mode and loaded with Zod 3.25 and Zod 4):
import { z } from "zod";
export const BaseSchema = z.object({
id: z.string(),
});
export type Base = z.infer<typeof BaseSchema>;
export interface Category { name: string; children: Category[] }
export const CategorySchema: z.ZodType<Category> = z.object({
name: z.string(),
children: z.array(z.lazy(() => CategorySchema)),
});
export const MenuSchema = BaseSchema.extend({
root: CategorySchema,
}).catchall(z.unknown());
export type Menu = z.infer<typeof MenuSchema>;
Example
Given this TypeScript input:
interface Address {
street: string;
city: string;
zipCode?: string;
}
export interface User {
id: number;
name: string;
role: "admin" | "user" | "guest";
age?: number;
isActive: boolean;
tags: string[];
address: Address;
}
export type Status = "active" | "inactive" | "pending";
The tool generates:
import { z } from "zod";
export const AddressSchema = z.object({
street: z.string(),
city: z.string(),
zipCode: z.string().optional(),
});
export type Address = z.infer<typeof AddressSchema>;
export const UserSchema = z.object({
id: z.number(),
name: z.string(),
role: z.enum(["admin", "user", "guest"]),
age: z.number().optional(),
isActive: z.boolean(),
tags: z.array(z.string()),
address: AddressSchema,
});
export type User = z.infer<typeof UserSchema>;
export const StatusSchema = z.enum(["active", "inactive", "pending"]);
export type Status = z.infer<typeof StatusSchema>;
Example: A Signup Form
Input:
interface SignupForm {
email: string;
password: string;
nickname?: string;
referrer: string | null;
age?: number | undefined;
plan: "free" | "pro";
}
Output:
import { z } from "zod";
export const SignupFormSchema = z.object({
email: z.string(),
password: z.string(),
nickname: z.string().optional(),
referrer: z.union([z.string(), z.null()]),
age: z.union([z.number(), z.undefined()]).optional(),
plan: z.enum(["free", "pro"]),
});
export type SignupForm = z.infer<typeof SignupFormSchema>;
Running the generated schema with zod 3.25 on three payloads:
SignupFormSchema.safeParse({ email: "not-an-email", password: "1", referrer: null, plan: "pro" })
// success: true (types match; no format rules yet)
SignupFormSchema.safeParse({ email: "a@example.com", password: "x", plan: "free" })
// referrer: Invalid input (string | null is required, it cannot be missing)
SignupFormSchema.safeParse({ email: "a@example.com", password: "x", referrer: "ad", plan: "team" })
// plan: Invalid enum value. Expected 'free' | 'pro', received 'team'
null, undefined and Optional
prop?: Tbecomes.optional(): the key may be missing.T | nullbecomesz.union([T, z.null()])— the same asT.nullable(): the key must be present, and its value may benull. A payload withoutreferrerfails.prop?: T | nullbecomesz.union([T, z.null()]).optional(): the key may be missing ornull, the same asT.nullish().
Adding the Rules TypeScript Cannot Express
TypeScript types have no formats or ranges, so the first payload above passes with an invalid email and a one-character password. Add refinements after generating:
export const SignupFormSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
nickname: z.string().max(20).optional(),
referrer: z.string().nullable(),
age: z.number().int().min(13).optional(),
plan: z.enum(["free", "pro"]),
});
Keep the generated z.infer type as the single source of truth and delete the original interface, so the two cannot drift apart.
Errors
The status line shows Parse error: followed by the first token the parser did not expect. A missing closing brace in interface A { a: string gives Expected "}" got "", and type = string gives Expected identifier, got "=". Input with no interface or type declaration, such as a file of const statements, gives “No interface or type declarations found.” A property without a colon is reported with its position instead of being skipped: line 3 of
interface User {
id: string;
age number;
}
gives Parse error: Line 3, column 3: "age" needs ":" before its type. Columns count characters, so an emoji or a Chinese character is one column.
Limitations
The tool reads declarations with its own small parser rather than the TypeScript compiler, so it does not resolve types from other files and does not type-check. Check the output for these cases before you use it:
- Unknown names become
z.unknown(). Any type not declared in the input, includingDateand imported types, is written asz.unknown() /* Name */. Replace it withz.date()or the imported schema. A base type that is not declared gives a plainz.object()with the comment/* extends Name: not declared in the input */. - Enums are copied as values. The schema checks the enum's values (
"RED",0), not the runtime enum object; if you import the enum,z.nativeEnum(Color)(Zod 3) orz.enum(Color)(Zod 4) does the same. Members with computed values such as1 << 2make the whole enumz.unknown() /* enum E: computed member A */. - Index signature keys are always
z.string(), because every key of a parsed JSON object is a string;[id: number]: Vis converted the same way. With.catchall(), a declared property must also match its own schema. - Records with literal keys such as
Record<"read" | "write", boolean>becomez.record(z.enum(["read", "write"]), z.boolean()). Zod 4 then requires both keys, as TypeScript does; Zod 3 accepts an object with only one of them. - Unicode escapes in names are not decoded.
\u0061: stringbecomes a property namedu0061, nota. - Only the colon is read in full width. Names follow TypeScript's Unicode identifier rules (
prénom: string,interface Caféand名前: stringare kept as written), and a full-width colon:outside string literals is read as:. Other full-width symbols are skipped:age?: numbergives a requiredage: z.number(). - Not converted: generic parameters (a recursive generic type also needs its written-out type fixed by hand), classes, methods, get / set accessors and call or construct signatures (skipped), mapped and conditional types,
keyof,typeofand template literal types (written asz.string()).
For JSON you already have, the JSON to Zod tool infers a schema from sample data instead of from types.
FAQ
What TypeScript constructs does this tool support?
It supports interface and type alias declarations, including basic types (string, number, boolean, null, undefined, any, unknown), optional properties (?), union types (A | B), string enums (literal unions), enum declarations, extends, index signatures, recursive types, arrays (T[] and Array<T>), nested inline objects, cross-references between declared types, and generic utilities like Partial<T>, Record<K, V>, Array<T>, and Promise<T>.
How are cross-references between types handled?
If you declare multiple interfaces or type aliases in the input, any reference to a declared type by name is replaced with its Schema constant. For example, a field typed as Address becomes AddressSchema in the output. Types not declared in the input become z.unknown() with a comment.
What Zod version does the output target?
The output uses APIs that exist in both Zod 3 and Zod 4: z.object(), z.string(), z.union(), z.enum(), z.array(), .optional(), z.literal(), z.record(key, value), .extend(), .shape, .catchall(), z.lazy(), z.ZodType and z.infer<>. Record types are written with an explicit key schema because Zod 4 no longer accepts z.record(value) alone. Promise<T> becomes z.promise(), which Zod 4 marks as deprecated.
How does the tool handle string union types?
A union of string literals like "admin" | "user" | "guest" is automatically converted to z.enum(["admin", "user", "guest"]) for conciseness. Mixed unions (e.g. string | null) use z.union([z.string(), z.null()]).
Can I convert TypeScript class or generic type definitions?
No. Class declarations are skipped, so input that has only classes gives "No interface or type declarations found." Type parameters of a declared type are not expanded: in interface Box<T> { value: T }, value becomes z.unknown() /* T */. Generic utility types applied to concrete types (Array<string>, Record<string, number>) are supported.
Is my code sent to a server?
No. The parser and the Zod generator run in this browser tab. Your code is not sent to a server and is not saved in browser storage. The page statistics record one usage event (the tool name and the action generate) when you edit the input and move the focus out of it, or click Example, and never include the code.