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
Normalize JSON-facing TypeScript schema types so serialized string-enum values are accepted without casts or diagnostic suppression.
Preserve recursive validation for nested objects, arrays, tuples, optional properties, unions, and index signatures while leaving numeric-enum behavior unchanged.
Add regression coverage for valid values, unknown values, differing member names/values, enum-member types, computed literal values, and unrelated type errors.
Document JSON string-enum behavior and the supported scope for computed members.
Validation
npm test — 184/184 tests pass
npm run build-all — all workspaces build successfully
The reason will be displayed to describe this comment to others. Learn more.
AI-assisted review: changes requested
This review was prepared with GitHub Copilot and is submitted at robgruen's explicit request.
The intent is worthwhile and matches the acceptance criteria in #465: validate serialized string-enum values without casts, suppressed diagnostics, or executing schema code. The focused documentation and regression coverage are useful. However, I reproduced two compatibility regressions that should be addressed before merging; the inline comments include sample code and observed results:
The recursive normalization erases call and constructor signatures. Previously rejected JSON can now pass validation even in schemas without enums. This also makes Promise-shaped JSON pass when combined with main's standard-library helper support. Preserve rejection of these non-JSON types and add negative regression tests.
Missing-property diagnostics unwrap unrelated generic types. With a custom createModuleTextFromJson implementation, a declaration targeting Wrapper<Metadata> reports missing fields from Metadata rather than the wrapper. Restrict unwrapping to the generated JSON-wire helper and add coverage for custom generic declarations.
Verification and separate baseline concern
Reviewed PR head e2f3f7bc7ce60083b5a20d2eff5eabf45ad689de using Node.js 24.22.1 and the existing installed dependencies; this was not a fresh npm ci run.
The library build and test compilation passed. The validator suite passed 19/19 tests on the PR head and 40/40 after a local merge with then-main d2a5a3ffe6e2962d36781d861a2feb6fae406573.
Additional before/after probes reproduced both regressions, including after merging that main baseline. Optional tuples and recursive enum schemas also behaved as intended in the extra probes.
Current main has since advanced to 137c5e1982323878866b5620c1f552cef16c6c80; I checked the intervening diff. It only adds validator cleanup in tests and does not change the validation logic or the examples runner discussed below.
Full npm test on the PR head produced 162 passes and one failed test-file startup, rather than a fully green run. The unchanged typescript/tests/examples.test.mjs:56 fails before discovering its tests:
I reproduced that same startup failure on the main baseline. This is a pre-existing validation limitation, not an enum regression or a request to add an unrelated fix to this PR. GitHub currently reports only the CLA check for this PR, so I also do not have an automated TypeScript test result confirming the stated full-suite pass. Please provide updated, reproducible test evidence with the revision and distinguish any remaining baseline failure from these two requested fixes.
The reason will be displayed to describe this comment to others. Learn more.
Preserve rejection of callable/constructable types when normalizing enums.
The T extends object branch maps functions and constructor types through keyof, which erases their signatures and can turn them into permissive empty-object types. This changes validation even when the schema contains no enums.
For example, using the built checkout's typechat/ts entry point:
The main baseline rejects both inputs. Neither an empty JSON object nor any other JSON value satisfies these call/construct signatures; accepting them returns data that does not satisfy the original schema.
After combining this change with main's standard-library helper support from #461, the same issue also affects Promise:
Main rejects that input. This Promise example requires main's helper declarations; the callable and constructor examples reproduce directly on the PR head. The existing Promise negative tests on main do not cover the case where both method names are present.
Please retain rejection of non-JSON call/construct signatures while normalizing string enums, and add negative tests for these cases. There should be an explicit validation failure, not a successful result with an incompatible value.
The reason will be displayed to describe this comment to others. Learn more.
Only unwrap the generated JSON-wire alias, not every generic type reference.
createModuleTextFromJson is a public, replaceable hook. A custom implementation can legitimately emit a declaration annotated with a generic schema type. Taking its first type argument unconditionally changes the target used to reconstruct TS2740 diagnostics.
Reproduction using the built checkout's typechat/ts entry point:
Type '{ payload: { m1: string; m2: string; m3: string; m4: string; m5: string; m6: string; m7: string; }; }' is missing the following properties from type 'Metadata': m1, m2, m3, m4, m5, m6, m7
The main baseline correctly reports:
Type '{ payload: { m1: string; m2: string; m3: string; m4: string; m5: string; m6: string; m7: string; }; }' is missing the following properties from type 'Wrapper<Metadata>': a, b, c, d, e, f, g
All metadata fields are already present inside payload; the missing fields belong to the wrapper. Returning the wrong target and property list also gives the repair loop misleading instructions.
Please verify that the annotation actually references this validator's generated helper before unwrapping it. Other generic annotations should retain their complete target type. Add a regression test with a custom module generator and enough missing wrapper fields to trigger TS2740.
Thanks robgruen — both compatibility regressions are fixed in 2634316.
The JSON-wire normalization now preserves call and construct signatures instead of mapping them through keyof, so {} no longer satisfies () => string or new () => …. This also keeps Promise-like then/catch methods callable and rejects non-callable stand-ins.
TS2740 diagnostic expansion now unwraps only the validator's own __TypeChatJsonWire annotation. Custom createModuleTextFromJson declarations such as Wrapper<Metadata> keep their full generic target and report the wrapper's missing fields.
Added regression coverage for call signatures, construct signatures, non-callable Promise-shaped objects, and a custom generic module generator.
Verification on 2634316 (Node 24.11.1, existing installed dependencies):
npm run build — passed
npx tsc -p test — passed
npm test — 187/187 tests passed, 0 failed
The full suite, including tests/examples.test.mjs, is green in this environment.
Adds support for validating JSON-serialized string enums by introducing a “wire” type wrapper during TypeScript assignment checks, along with new tests and documentation describing the behavior.
Changes:
Add a generated __TypeChatJsonWire<T> helper type to accept serialized string-enum values during validate().
Extend the test suite with coverage for string enums across nested shapes and for diagnostic targeting with custom module text.
Document how string enums are validated from JSON in the TypeScript basic usage guide.
File
Description
typescript/src/ts/validate.ts
Generates and uses a unique JsonWire helper type in the emitted module text; adjusts missing-property expansion to avoid unwrapping custom type annotations.
typescript/test/validate.test.ts
Adds test cases for serialized string enums (including nested usage) and for diagnostics when custom module text is used.
site/src/docs/typescript/basic-usage.md
Documents string-enum JSON representation and how the validator handles it (including computed members).
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Normalization weakens validation by dropping private/protected class constraints and converting the broad object type to {}, allowing previously rejected values.
Mapping the broad object type loses its non-primitive constraint: keyof object is never, so this branch produces {}, which also accepts strings, numbers, and booleans. For example, export interface Response { value: object } now accepts { value: 123 }, whereas the original assignment rejects it. Preserve types with no keys instead of mapping them to {}, and add a regression test that rejects primitive values for an object property.
Mapped types drop private and protected class member constraints
typescript/src/ts/validate.ts:63
The mapped-object branch drops private and protected class members because they are excluded from keyof T, weakening validation even for schemas without enums. For example, export declare class Token { private value: string; label: string; } used by Response { token: Token } now accepts { token: { label: "x" } }, whereas the original assignment rejects it. Preserve private/protected class constraints during normalization and add a regression case with both private and public members.
The reason will be displayed to describe this comment to others. Learn more.
AI-assisted follow-up review: changes requested
This review was prepared with GitHub Copilot and is submitted at robgruen's explicit request.
Thanks for addressing the earlier callable/constructor and custom-generic diagnostic findings. Those cases now behave correctly in my checks on 05788e4823d6369f626c079c19c656de63a8dd66. The string-enum support, focused documentation, and regression coverage remain useful.
Two issues still need attention before merging; both inline comments include runnable reproductions:
The recursive mapped type drops class-instance constraints. A plain JSON object now satisfies a class-typed property despite lacking its required private member. The pre-PR assignment rejects the same input. This affects schemas without enums and conflicts with #465's requirement to preserve the rest of the schema's validation.
The latest multiline refactor breaks the generated-module test. The helper now contains a newline after =, while the assertion still requires a single-line substring. Please make the assertion whitespace-independent.
Verification
Reviewed exact head 05788e4823d6369f626c079c19c656de63a8dd66.
Node.js 24.22.1, TypeScript 7.0.2, using existing installed dependencies rather than a fresh npm ci.
Library build and test compilation passed.
Focused validator suite: 59 passed, 1 failed. The failing test is produces valid TypeScript module text for a simple object; this is a failure introduced by the latest revision, not the previously reported baseline issue.
Additional before/after probes confirmed the class-instance regression and checked enum behavior and the earlier callable/constructor fixes.
I did not run the full suite. GitHub currently exposes only the successful CLA check for this head.
Please fix these two issues, add the class-instance regression test, and provide updated validation results.
The reason will be displayed to describe this comment to others. Learn more.
Preserve class-instance constraints when recursively normalizing enum values.
keyof T excludes private/protected members, so rebuilding every object as a mapped type also strips class-instance constraints. This is another case where normalization accepts JSON that the original schema rejects, even when there are no enums.
From the TypeScript package directory, run npm run build, then save the following as repro-enum-wire.cjs in that directory and run node repro-enum-wire.cjs:
const{ createTypeScriptJsonValidator }=require("typechat/ts");constschema=`export class Token { private brand!: string; value!: string;}export interface Response { token: Token;}`;constvalidator=createTypeScriptJsonValidator(schema,"Response");constinput={token: {value: "unbranded"}};try{console.log("PR generator:",validator.validate(input));// Restore the pre-PR assignment generator as a control.validator.createModuleTextFromJson=value=>({success: true,data: `import { Response } from './schema';const json: Response = ${JSON.stringify(value)};`});console.log("Pre-PR assignment:",validator.validate(input));}finally{validator.close();}
On 05788e4, the first result has success: true. The control has success: false with:
Property 'brand' is missing in type '{ value: string; }' but required in type 'Token'.
The expected behavior is rejection in both cases: this JSON does not satisfy the original Token type. Please preserve that rejection while normalizing enums, and add negative regression coverage for class-instance constraints in an enum-free schema. Keep the existing serialized-enum cases passing.
The reason will be displayed to describe this comment to others. Learn more.
Make this assertion independent of helper formatting.
The latest commit emits type __TypeChatJsonWire<T> = followed by a newline and indentation before T extends string. This exact single-line substring therefore no longer exists, and the validator suite fails.
From the TypeScript package directory, the focused reproduction is:
npm run build
npm exec --no -- tsc -p test
node --test --test-name-pattern="produces valid TypeScript module text for a simple object" .\out\validate.test.js
It fails at this assertion with ERR_ASSERTION. A standalone JavaScript reproduction, after building, is below; save it as repro-module-text.cjs in the same directory and run node repro-module-text.cjs:
constassert=require("node:assert/strict");const{ createTypeScriptJsonValidator }=require("typechat/ts");constvalidator=createTypeScriptJsonValidator("export interface Point { x: number; y: number; }","Point");try{constresult=validator.createModuleTextFromJson({x: 1,y: 2});assert.ok(result.success);console.log(JSON.stringify(result.data));assert.ok(result.data.includes("type __TypeChatJsonWire<T> = T extends string"));}finally{validator.close();}
Please use a whitespace-independent assertion, for example:
On Node 24.22.1 / TypeScript 7.0.2, the full focused validator file currently has 59 passes and this one failure. Please rerun it after the update and refresh the PR's validation results.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Object normalization erases private/protected nominal constraints, allowing previously rejected values, and a whitespace-sensitive test assertion fails on valid generated output.
assert.ok(!factory.success, "expected an empty object not to satisfy a construct signature");
assert.match(factory.message, /not assignable/);
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.
Summary
Validation
npm test— 184/184 tests passnpm run build-all— all workspaces build successfullyFixes #465