TypeScript 转 Zod Schema
在线将 TypeScript interface 和 type 声明转换为 Zod 验证 schema,支持联合类型、可选属性、数组、枚举、嵌套对象及类型交叉引用。免费,在浏览器中处理。
- 在浏览器中处理
- 工具不会把输入上传到 ZeroTool 服务器
- 免费 · 无需注册
用微信扫描以下二维码即可分享
示例、说明与常见问题 带实际输出的示例、与同类工具的差别,以及常见问题。
支持的 TypeScript 特性
- 基础类型:
string、number、boolean、null、undefined、any、unknown、void、never、bigint、symbol - 可选属性:
prop?: type→.optional() - 联合类型:
A | B→z.union([A, B]) - 字符串枚举:
"a" | "b" | "c"→z.enum(["a", "b", "c"]) - 数组:
T[]/Array<T>→z.array(T) - 嵌套对象:内联对象类型 →
z.object({}) - 交叉引用:命名类型间相互引用 → Schema 常量
- readonly:接受
readonly修饰符,转换时去掉;需要只读的推断类型时自行加.readonly() - 工具类型:
Partial<T>、Record<K, V>、Promise<T> - 交叉类型:
A & B→z.intersection(A, B) - 元组:
[A, B]→z.tuple([A, B]) - 字面量类型:
"value"、42、true→z.literal() extends:interface Admin extends Base→BaseSchema.extend({ ... }),第二个父类型追加.extend(OtherSchema.shape);父类型不是对象 schema(如交叉类型别名)时写成z.intersection(BaseSchema, z.object({ ... }))。未在输入中声明的父类型生成普通z.object()并加注释。- 索引签名:与其他属性并存的
[key: string]: V→.catchall(V)(校验并保留多出来的键);只有索引签名时 →z.record(z.string(), V)。键总是z.string(),因为解析出的 JSON 对象的键都是字符串。 enum声明:字符串枚举 → 取值的z.enum();数字或混合成员(从 0 或上一个数字自动递增)→z.literal()的z.union()。const enum、declare enum同样处理;含1 << 2这类计算值的枚举整体写成z.unknown()并加注释。- 声明顺序与递归:不论输入顺序,被依赖的 schema 先输出。形成环的引用写成
z.lazy(() => NameSchema),环上的每个类型照原文写出并加z.ZodType<Name>标注(Zod 文档里递归类型的写法)。输出已用 TypeScript 5.9 严格模式编译,并在 Zod 3.25 与 Zod 4 下加载验证。
示例
给定以下 TypeScript 输入:
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";
工具生成:
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>;
示例:微信支付回调通知
微信支付「支付成功回调通知」文档(更新时间 2024.12.27)列出了回调报文的通知参数:event_type 在支付成功时为 TRANSACTION.SUCCESS,resource_type 固定为 encrypt-resource,resource 里的 algorithm 目前为 AEAD_AES_256_GCM,associated_data 选填。按这张表写成 interface,固定值用字面量类型:
interface WechatPayNotify {
id: string;
create_time: string;
event_type: "TRANSACTION.SUCCESS";
resource_type: "encrypt-resource";
summary: string;
resource: {
original_type: "transaction";
algorithm: "AEAD_AES_256_GCM";
ciphertext: string;
associated_data?: string;
nonce: string;
};
}
工具输出:
import { z } from "zod";
export const WechatPayNotifySchema = z.object({
id: z.string(),
create_time: z.string(),
event_type: z.literal("TRANSACTION.SUCCESS"),
resource_type: z.literal("encrypt-resource"),
summary: z.string(),
resource: z.object({
original_type: z.literal("transaction"),
algorithm: z.literal("AEAD_AES_256_GCM"),
ciphertext: z.string(),
associated_data: z.string().optional(),
nonce: z.string(),
}),
});
export type WechatPayNotify = z.infer<typeof WechatPayNotifySchema>;
单个字符串字面量生成 z.literal(),两个以上才合成 z.enum()。文档里的示例报文能通过这个 schema,去掉 associated_data 也能通过;缺少 resource,或 resource_type 不是 encrypt-resource 的报文会失败。嵌套对象的属性比常见写法多缩进两格,这是工具的输出格式,不影响运行,可以交给 Prettier 重新排版。
这个 schema 只检查通知的外层结构。ciphertext 解密后才是订单信息,那部分 JSON 需要另写一个 interface 再生成。验签必须在解析之前用原始报文完成,parse() 返回的对象会去掉 schema 里没有的键,不能拿来重新拼验签串。
示例:注册表单
输入:
interface SignupForm {
email: string;
password: string;
nickname?: string;
referrer: string | null;
age?: number | undefined;
plan: "free" | "pro";
}
输出:
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>;
用 zod 3.25 拿生成的 schema 校验三份数据:
SignupFormSchema.safeParse({ email: "not-an-email", password: "1", referrer: null, plan: "pro" })
// success: true (类型都对;还没有格式规则)
SignupFormSchema.safeParse({ email: "a@example.com", password: "x", plan: "free" })
// referrer: Invalid input (string | null 必须有这个键,不能缺)
SignupFormSchema.safeParse({ email: "a@example.com", password: "x", referrer: "ad", plan: "team" })
// plan: Invalid enum value. Expected 'free' | 'pro', received 'team'
null、undefined 与可选
prop?: T变成.optional():这个键可以不存在。T | null变成z.union([T, z.null()]),等价于T.nullable():键必须存在,值可以是null。缺少referrer的数据会校验失败。prop?: T | null变成z.union([T, z.null()]).optional():键可以不存在,值也可以是null,与T.nullish()相同。
中文名称与全角冒号
属性名和类型名按 TypeScript 的标识符规则读取,可以直接写中文。中文输入法打出的全角冒号 : 在字符串字面量之外按半角 : 读取。下面这段 interface 里,备注 没加引号,amount 后面是全角冒号:
interface Order {
id: string;
amount:number;
备注: string;
"收货人": string;
}
import { z } from "zod";
export const OrderSchema = z.object({
id: z.string(),
amount: z.number(),
备注: z.string(),
"收货人": z.string(),
});
export type Order = z.infer<typeof OrderSchema>;
四个属性都在:amount 是 z.number(),备注 原样作为属性名,加了引号的 "收货人" 保留引号。只把冒号当作例外处理,是因为对整段输入做 NFKC 会连字符串字面量类型一起改掉("AB" 会变成 "AB")。类型名同样可以是中文,interface 订单 生成 订单Schema。
漏写冒号时会报错并给出位置,不再跳过这个属性。输入:
interface 订单 {
id: string;
amount number;
}
状态栏显示 解析错误:第 3 行第 3 列:“amount”后面缺少冒号“:”。,输出清空。列号按字符计,一个汉字算一列。其他语法错误的正文仍是英文,只给出解析器没料到的第一个记号:缺少右花括号的 interface A { a: string 报 Expected "}" got "",只有 const 语句的输入提示「未找到 interface 或 type 声明。」。
补上 TypeScript 表达不了的规则
TypeScript 类型没有格式和范围,所以上面第一份数据带着无效邮箱和一位密码也通过了。生成后补上约束:
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"]),
});
之后把生成的 z.infer 类型当作唯一来源,删掉原来的 interface,两者就不会逐渐不一致。
限制
工具用自带的小型解析器读取声明,没有调用 TypeScript 编译器,不会跨文件解析类型,也不做类型检查。使用前请核对以下几处:
- 未声明的名字变成
z.unknown()。输入里没有声明的类型(包括Date和从别处 import 的类型)写成z.unknown() /* Name */,请换成z.date()或对应的 schema。父类型没有声明时生成普通z.object(),并加注释/* extends Name: not declared in the input */。 - enum 按值复制。schema 检查的是枚举的值(
"RED"、0),不是运行时的枚举对象;如果项目里能 import 这个 enum,用z.nativeEnum(Color)(Zod 3)或z.enum(Color)(Zod 4)效果相同。 - 索引签名的键总是
z.string();与.catchall()并用时,声明过的属性也要符合自己的 schema。 - 字面量键的 Record,如
Record<"read" | "write", boolean>,生成z.record(z.enum(["read", "write"]), z.boolean())。Zod 4 要求两个键都在,与 TypeScript 一致;Zod 3 只有一个键也通过。 - 名字里的 Unicode 转义不会解码。
\u0061: string生成名为u0061的属性,不是a。 - 只有冒号按全角读取。全角问号等其他符号仍按未知字符跳过:
age?: number生成必填的age: z.number(),不会变成可选。 - 不转换:泛型参数、class、方法、get / set 访问器、调用签名与构造签名(跳过)、映射类型与条件类型、
keyof、typeof,模板字面量类型写成z.string()。
FAQ
支持哪些 TypeScript 语法结构?
支持 interface 和 type alias 声明,包括基础类型(string、number、boolean、null、undefined、any、unknown)、可选属性(?)、联合类型(A | B)、字符串枚举(字面量联合)、enum 声明、extends、索引签名、递归类型、数组(T[] 和 Array<T>)、嵌套内联对象、声明类型间的交叉引用,以及 Partial<T>、Record<K, V>、Array<T>、Promise<T> 等泛型工具类型。
类型间的交叉引用如何处理?
如果输入中声明了多个 interface 或 type alias,对某个已声明类型名称的引用会被替换为对应的 Schema 常量。例如,字段类型为 Address 的会在输出中变为 AddressSchema。输入中未声明的类型则变为 z.unknown()(附带注释)。
生成的 Schema 兼容哪个版本的 Zod?
输出只用 Zod 3 与 Zod 4 都有的 API:z.object()、z.string()、z.union()、z.enum()、z.array()、.optional()、z.literal()、z.record(键, 值)、.extend()、.shape、.catchall()、z.lazy()、z.ZodType 和 z.infer<>。Record 类型总是写出键的 schema,因为 Zod 4 不再接受只有值的 z.record()。Promise<T> 生成的 z.promise() 在 Zod 4 中已标为弃用。
字符串联合类型如何处理?
字符串字面量联合(如 "admin" | "user" | "guest")会自动转换为 z.enum(["admin", "user", "guest"]) 以保持简洁。混合联合类型(如 string | null)则使用 z.union([z.string(), z.null()])。
可以转换 TypeScript class 或泛型类型吗?
不能。class 声明会被跳过,只有 class 的输入会提示「未找到 interface 或 type 声明。」。已声明类型自己的类型参数不会展开:interface Box<T> { value: T } 里的 value 生成 z.unknown() /* T */。应用于具体类型的泛型工具类型(Array<string>、Record<string, number>)是支持的。
代码会被发送到服务器吗?
不会。解析器和 Zod 生成器在当前浏览器标签页里运行,代码不会发送到服务器,也不会保存到浏览器存储。页面统计只在你编辑完输入框、焦点移开时,或点击「示例」时记录一次使用事件(工具名和动作 generate),不包含代码内容。