Zod Schema验证报错:TypeError: 无法读取undefined的'extend'属性
Zod 报错:TypeError: Cannot read properties of undefined (reading 'extend') 解决方案
使用Zod进行Schema验证时出现TypeError: Cannot read properties of undefined (reading 'extend'),TypeScript可识别Base schema的extend方法,但运行时报错持续存在,相关代码如下:
原出错代码
base.policy.ts
import * as z from "zod"; const Base = z.object({ one: z.any(); two: z.any(); }) export { Base };
three.policy.ts
import * as z from "zod"; import { Base } from "./"; const Extended = Base.extend({ three: z.any(); })
问题原因及解决办法
- 语法错误导致导出失败:原代码中Zod对象的属性结尾使用了分号
;,不符合对象字面量语法规范,会导致Base变量未被正确创建和导出。需将分号改为逗号,。 - 导入路径错误:
three.policy.ts中import { Base } from "./";未指定具体文件,除非目录下有index.ts导出Base,否则无法正确导入。需明确指向base.policy.ts文件,改为import { Base } from "./base.policy";(TS项目可省略.ts后缀)。 - Zod版本兼容性:确认安装的Zod版本为v3及以上,
extend方法在Zod v3中才稳定支持,若版本过低请执行npm install zod@latest升级。
修正后的代码
base.policy.ts
import * as z from "zod"; const Base = z.object({ one: z.any(), two: z.any(), }); export { Base };
three.policy.ts
import * as z from "zod"; import { Base } from "./base.policy"; const Extended = Base.extend({ three: z.any(), });
内容的提问来源于stack exchange,提问作者pi88a
相关产品推荐
相关产品推荐

