You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat(zod): emit typed schemas for Set and Map collections (#451) - #535
Related to #451 by emitting typed schemas for z.set() and z.map() in getZodSchemaAsTypeScript instead of falling through to any, and adding explicit regression tests for JSON-to-collection transformations.
Context & Motivation
When generating prompt schemas with getZodSchemaAsTypeScript, z.set() and z.map() previously lacked explicit handlers in the type switch and fell through to any.
This PR provides:
Direct collection schema emission: globalThis.Set<T> and globalThis.Map<K, V> in TypeScript schemas matching standard library declarations while preventing naming collisions when user schemas are named Set or Map.
Verified explicit wire-to-runtime transforms: in TypeChat applications using z.array(...).transform(v => new Set(v)) and z.array(z.tuple(...)).transform(v => new Map(v)), the wire schema emits JSON-compatible arrays (T[] and [K, V][]) while validation cleanly hydrates runtime Set and Map instances.
Changes
typescript/src/zod/validate.ts:
Qualified emitted built-ins as globalThis.Set<T> and globalThis.Map<K, V> to prevent shadowing when callers name schemas Set or Map.
typescript/test/zod.test.ts:
Added compiler-backed regression tests for colliding schema names ({ Set: z.set(...) } and { Map: z.map(...) }), verified with TypeScript compilation via assertSchemasCompile.
Added regression tests for explicit z.array(...).transform(...) wire schema emission and validation hydration into Set and Map instances.
Added end-to-end translation test with createJsonTranslator and a stubbed model.
Validation
npm run build-all: Clean build across core and all sample workspaces.
npm test: 379 tests passed, 0 failed (67 test suites).
Zod `z.set()` and `z.map()` previously fell through to `any` in
`getZodSchemaAsTypeScript`.
This change:
- Emits `T[]` for `z.set()` as the JSON-compatible wire schema.
- Emits `[K, V][]` for `z.map()` as the key-value tuple array wire schema.
- Adds test coverage for `z.set()` and `z.map()` in `test/zod.test.ts`,
including union elements.
Closesmicrosoft#451
Signed-off-by: Utkarsh patwa <utkarshpatwa393@gmail.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Bare z.set() and z.map() schemas reject the translator’s plain JSON arrays, causing even schema-conforming responses to fail validation with no repair path to the required collection instances.
Utkarsh Patwa (utkarshpatwa393-sys)
changed the title
feat(zod): emit typed wire schemas for Set and Map collections (#451)
feat(zod): emit typed schemas for Set and Map collections (#451)
Nov 19, 2026
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Caller-supplied schema names can shadow the generated Set and Map references, causing TypeScript compilation failures unless both references are qualified with globalThis.
Thanks for adding the end-to-end test. It makes the intended boundary clear: the model sends ordinary JSON arrays, and the explicit Zod transforms produce the runtime collections.
There is one remaining compiler issue in f2bc01e. An application picks its own schema names. If it picks Set or Map, the generated alias hides the standard-library type it was meant to reference:
Schema passed to getZodSchemaAsTypeScript
Generated TypeScript
{ Set: z.set(z.string()) }
type Set = Set<string>;
{ Map: z.map(z.string(), z.number()) }
type Map = Map<string, number>;
I checked those two declarations in an isolated module with the repo's TypeScript 7.0.2 compiler (--strict --noEmit, ES2022). Both produce TS2456 (the alias circularly references itself) and TS2315 (the local alias is not generic). Changing only the right-hand sides to globalThis.Set<string> and globalThis.Map<string, number> compiles cleanly with the same options. This was a focused compiler check, not a run of the full PR suite.
Could you qualify the emitted built-in names and add compiler-backed regression cases for both of the schema maps above? Using Set and Map as the caller's names, rather than T, is what catches the regression. That would address the remaining inline thread.
One small scope request: would you mind changing the PR description from Fixes #451 to Related to #451? These collection tests are a useful contribution. Issue #451's scope also includes copyable TypeScript and Zod examples, duplicate handling, and behavior with repair enabled or disabled. A non-closing reference gives this work credit and keeps those items visible without asking you to take them all on here.
Copilot-assisted review, posted at the maintainer's request.
The reason will be displayed to describe this comment to others. Learn more.
Requesting changes on the remaining Set / Map schema-name collision. Could you qualify the built-in names, add the two compiler-backed regression cases, and make the reference to issue #451 non-closing? The examples, compiler results, and scope note have the details. The earlier JSON-input thread is resolved. Thanks for the explicit-conversion coverage; happy to take another look after the update.
Copilot-assisted review submitted at the maintainer's request.
Thank you for the detailed compiler inspection and guidance!
All points have been addressed in commit f8f58f5:
Qualified built-ins: Updated appendSetType and appendMapType to emit globalThis.Set<...> and globalThis.Map<...> in typescript/src/zod/validate.ts.
Compiler-backed regression cases: Added regression tests in typescript/test/zod.test.ts for schemas explicitly named Set and Map:
schemaOf("Set", z.set(z.string()))
schemaOf("Map", z.map(z.string(), z.number()))
Both are compiled via assertSchemasCompile using the project's TypeScript compiler, cleanly resolving TS2456 and TS2315 without collisions.
Scope note: Updated the PR description from Fixes #451 to Related to #451.
All 379 tests across 67 test suites pass cleanly (npm test). Ready for your re-review! Thank you.
The reason will be displayed to describe this comment to others. Learn more.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Collection schema generation can overflow the stack for unnamed recursive objects and emit invalid TypeScript for non-identifier property names.
No open issues 🎉
2 previously missed issues
In code that hasn't changed since last review
Unnamed recursive collection schemas overflow the stack
typescript/src/zod/validate.ts:207
An unnamed recursive object inside a collection now causes schema generation to overflow the stack—for example, Node with a children getter returning z.set(Node).optional(). Detect types already being expanded and report a clear error telling callers to register the recursive type by name, with regression tests for both collections. Same issue in typescript/src/zod/validate.ts:216 for map values.
Collection schemas emit invalid TypeScript for non-identifier keys
typescript/src/zod/validate.ts:207
z.set(z.object({ "part-number": z.string() })) now emits part-number: string; without quotes, producing invalid TypeScript. Escape non-identifier property names in both required and optional branches of appendObjectType, and add collection regression tests. The same issue affects map values at typescript/src/zod/validate.ts:216.
Thanks for addressing the feedback and adding the regression tests! I ran another Copilot review, which flagged two additional edge cases. Could you take a look at its latest findings?
…cursive collections (microsoft#451)
- In appendObjectType, escape non-identifier property names with JSON.stringify in both required and optional branches.
- In getZodSchemaAsTypeScript, track expanding type identities in expandingTypes to detect unnamed recursive types in collections or nested objects and throw an actionable error instructing callers to register the recursive type by name.
- Add compiler-backed regression tests in typescript/test/zod.test.ts for non-identifier keys in Set, Map, and object types, as well as unnamed and registered recursive schemas for both Set and Map.
Signed-off-by: Utkarsh Patwa <utkarshpatwa393@gmail.com>
The reason will be displayed to describe this comment to others. Learn more.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
Thank you for running the follow-up review! Both edge cases have been resolved in commit 56407db:
Non-Identifier Property Keys Escaping:
In appendObjectType, added isValidPropertyName check (/^[a-zA-Z_$][0-9a-zA-Z_$]*$/).
If a property name is not a standard identifier (e.g. "part-number", "is-active"), it is escaped using JSON.stringify(name) across both required ("part-number": string;) and optional ("is-active"?: boolean;) branches.
Added compiler-backed regression tests verifying quoted property emissions in Set element objects, Map value objects, and standalone object interfaces.
Unnamed Recursive Collection Schemas Detection:
In getZodSchemaAsTypeScript, introduced an expandingTypes = new Set<object>() tracking set.
When expanding type definitions in appendType, if a type identity is already in expandingTypes and unmapped in namedTypes (such as a recursive Node referencing itself via z.set(Node).optional() or z.map(..., Node).optional() without being registered in the top-level schema), an actionable error is immediately thrown:
Recursive type reference detected in schema. Register the recursive type by name in the schema object to allow named type reference emission.
When callers register the recursive type by name (schema: { Node, ... }), namedTypes resolves the reference cleanly to emit globalThis.Set<Node> / globalThis.Map<string, Node>.
Added regression tests for both Set and Map verifying both the diagnostic error on unregistered recursive types and valid compilation when registered by name.
Verification
npm run build-all: Clean build across core and all sample workspaces.
npm test: 386 tests pass (up from 379, 7 new tests passed, 0 failed across 67 suites).
The changes have been pushed to the PR branch. Ready for your review!
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
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.
Related to #451 by emitting typed schemas for
z.set()andz.map()ingetZodSchemaAsTypeScriptinstead of falling through toany, and adding explicit regression tests for JSON-to-collection transformations.Context & Motivation
When generating prompt schemas with
getZodSchemaAsTypeScript,z.set()andz.map()previously lacked explicit handlers in the type switch and fell through toany.This PR provides:
globalThis.Set<T>andglobalThis.Map<K, V>in TypeScript schemas matching standard library declarations while preventing naming collisions when user schemas are namedSetorMap.z.array(...).transform(v => new Set(v))andz.array(z.tuple(...)).transform(v => new Map(v)), the wire schema emits JSON-compatible arrays (T[]and[K, V][]) while validation cleanly hydrates runtimeSetandMapinstances.Changes
typescript/src/zod/validate.ts:globalThis.Set<T>andglobalThis.Map<K, V>to prevent shadowing when callers name schemasSetorMap.typescript/test/zod.test.ts:{ Set: z.set(...) }and{ Map: z.map(...) }), verified with TypeScript compilation viaassertSchemasCompile.z.array(...).transform(...)wire schema emission and validation hydration intoSetandMapinstances.createJsonTranslatorand a stubbed model.Validation
npm run build-all: Clean build across core and all sample workspaces.npm test: 379 tests passed, 0 failed (67 test suites).