fix: resolve TypeScript deep type instantiation error with Zod schemas#39
Merged
Conversation
Use type assertions (as any) to prevent TypeScript from recursively inferring deeply nested Zod types (ZodDefault<ZodOptional<...>>), which was causing TS2589 compilation errors. This approach maintains runtime type safety through Zod's schema validation while avoiding compiler recursion limits.
Contributor
|
可能这就是导致 #37 错误的原因 |
Owner
是的。 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
修复:解决 Zod schema 导致的 TypeScript 类型实例化过深错误
根本原因
类型嵌套过深: 使用 .optional().default() 链式调用创建的 Zod schema 生成了多层嵌套的类型结构 ZodDefault<ZodOptional>
递归推断触发限制: TypeScript 在推断 17 个工具的所有字段类型时,递归深度超过编译器限制(约 50 层)
累积效应: 多个工具 × 多个字段 × 多层嵌套 = 超过类型系统处理能力
解决方案
在类型推断边界使用 as any 断言,切断 TypeScript 的递归类型推断链:
安全性保证:
✅ 运行时类型安全由 Zod schema 验证保证
✅ MCP SDK 在运行时检查函数签名
✅ 仅在必要的类型边界使用 any,内部逻辑保持类型安全
fixed #38