Skip to content

fix(ts): accept serialized string enum values - #471

Open
与世无争剑宇子 (yushiwuzhengjianyuzi) wants to merge 4 commits into
microsoft:mainfrom
yushiwuzhengjianyuzi:fix/enum-wire-validation
Open

与世无争剑宇子 (yushiwuzhengjianyuzi) wants to merge 4 commits into
microsoft:mainfrom
yushiwuzhengjianyuzi:fix/enum-wire-validation

Conversation

@yushiwuzhengjianyuzi

Copy link
Copy Markdown
Contributor

Summary

  • 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

Fixes #465

@robgruen robgruen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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:

  1. 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.
  2. 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:
compilerOptions: { module: ts.ModuleKind.CommonJS, esModuleInterop: true },
                                         ^
TypeError: Cannot read properties of undefined (reading 'CommonJS')

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.

Comment thread typescript/src/ts/validate.ts Outdated
* rest of the schema's structure.
*/
function createJsonWireTypeDefinition(typeName: string): string {
return `type ${typeName}<T> = T extends string ? \`\${T}\` : T extends object ? { [K in keyof T]: ${typeName}<T[K]> } : T;`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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:

const { createTypeScriptJsonValidator } = require("typechat/ts");

function check(schema, input) {
    const validator = createTypeScriptJsonValidator(schema, "Response");
    try {
        return validator.validate(input);
    } finally {
        validator.close();
    }
}

console.log(JSON.stringify(check(
    "export interface Response { callback: () => string; }",
    { callback: {} }
)));
console.log(JSON.stringify(check(
    "export interface Response { factory: new () => { ok: boolean }; }",
    { factory: {} }
)));

Observed on this PR head:

{"success":true,"data":{"callback":{}}}
{"success":true,"data":{"factory":{}}}

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:

console.log(JSON.stringify(check(
    "export interface Response { value: Promise<string>; }",
    { value: { then: {}, catch: {} } }
)));

Observed after the local merge with main:

{"success":true,"data":{"value":{"then":{},"catch":{}}}}

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.

Comment thread typescript/src/ts/validate.ts Outdated
const targetType = checker.getTypeAtLocation(decl.type);
// The generated JSON declaration wraps the schema type in the JsonWire helper.
// Use the wrapped schema type for user-facing diagnostics.
const targetTypeNode = decl.type.typeArguments?.[0] ?? decl.type;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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:

const { createTypeScriptJsonValidator } = require("typechat/ts");

const schema = `
export interface Metadata {
    m1: string; m2: string; m3: string; m4: string;
    m5: string; m6: string; m7: string;
}
export interface Wrapper<T> {
    a: string; b: string; c: string; d: string;
    e: string; f: string; g: string; payload: T;
}
export type Response = Wrapper<Metadata>;
`;
const input = {
    payload: { m1: "", m2: "", m3: "", m4: "", m5: "", m6: "", m7: "" }
};
const validator = createTypeScriptJsonValidator(schema, "Response");
validator.createModuleTextFromJson = value => ({
    success: true,
    data: `import { Wrapper, Metadata } from './schema';\nconst json: Wrapper<Metadata> = ${JSON.stringify(value)};`
});
try {
    const result = validator.validate(input);
    if (!result.success) console.log(result.message);
} finally {
    validator.close();
}

The PR reports this incorrect diagnostic:

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me know if you want to continue work on this or if you me to hand it off to an agent for correction. Happy either way.

Copilot AI balanced review requested due to automatic review settings November 9, 2026 07:22
@yushiwuzhengjianyuzi

Copy link
Copy Markdown
Contributor Author

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.

Please take another look when you have a moment.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Copilot was unable to run its full agentic suite in this review.

Copilot review overview

3 open issues
What changed in this PR

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).

Review effort: Lite

Comment on lines +52 to +57
function createJsonWireTypeDefinition(typeName: string): string {
return `type ${typeName}<T> = T extends string ? \`\${T}\` : ` +
`T extends (...args: any[]) => any ? T : ` +
`T extends abstract new (...args: any[]) => any ? T : ` +
`T extends object ? { [K in keyof T]: ${typeName}<T[K]> } : T;`;
}
Comment thread typescript/test/validate.test.ts Resolved
Comment thread typescript/src/ts/validate.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Comment thread typescript/test/validate.test.ts Resolved
Comment on lines +376 to +385
it("rejects unknown values and member names that differ from their values", () => {
const v = validatorFor(differingEnumValueSchema, "Subscription");
const unknown = v.validate({ plan: "enterprise" });
assert.ok(!unknown.success, "expected an unknown enum value to fail");
assert.match(unknown.message, /not assignable/);

const memberName = v.validate({ plan: "Basic" });
assert.ok(!memberName.success, "expected an enum member name to fail when it differs from the value");
assert.match(memberName.message, /not assignable/);
});
Comment thread typescript/src/ts/validate.ts Resolved
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 10, 2026 20:52

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

2 open issues
2 previously missed issues

In code that hasn't changed since last review

High severity Mapping object to {} allows primitive values

typescript/​src/​ts/​validate.ts:63

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.

High severity 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.

4 resolved since last review

Review effort: Balanced

@robgruen robgruen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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:

  1. 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.
  2. 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.

T extends string ? \`\${T}\` :
T extends (...args: any[]) => any ? T :
T extends abstract new (...args: any[]) => any ? T :
T extends object ? { [K in keyof T]: ${typeName}<T[K]> } : T;`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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");

const schema = `
export class Token {
    private brand!: string;
    value!: string;
}
export interface Response {
    token: Token;
}`;

const validator = createTypeScriptJsonValidator(schema, "Response");
const input = { 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.

assert.ok(result.success, "expected module text creation to succeed");
assert.ok(result.data.includes("import { Point } from './schema'"));
assert.ok(result.data.includes("const json: Point ="));
assert.ok(result.data.includes("type __TypeChatJsonWire<T> = T extends string"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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:

const assert = require("node:assert/strict");
const { createTypeScriptJsonValidator } = require("typechat/ts");

const validator = createTypeScriptJsonValidator(
    "export interface Point { x: number; y: number; }",
    "Point"
);
try {
    const result = 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:

assert.match(result.data, /type __TypeChatJsonWire<T>\s*=\s*T extends string/);

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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

T extends string ? \`\${T}\` :
T extends (...args: any[]) => any ? T :
T extends abstract new (...args: any[]) => any ? T :
T extends object ? { [K in keyof T]: ${typeName}<T[K]> } : T;`;
assert.ok(result.success, "expected module text creation to succeed");
assert.ok(result.data.includes("import { Point } from './schema'"));
assert.ok(result.data.includes("const json: Point ="));
assert.ok(result.data.includes("type __TypeChatJsonWire<T> = T extends string"));
});
assert.ok(!invalid.success, "expected an unknown nested enum value to fail");
assert.match(invalid.message, /not assignable/);
});
Comment on lines +445 to +452
const v = validatorFor(callableSchema, "Response");
const callback = v.validate({ callback: {}, factory: { ok: true } });
assert.ok(!callback.success, "expected an empty object not to satisfy a call signature");
assert.match(callback.message, /not assignable/);

const factory = v.validate({ callback: () => "ok", factory: {} });
assert.ok(!factory.success, "expected an empty object not to satisfy a construct signature");
assert.match(factory.message, /not assignable/);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support serialized enum values with Zod-style schema normalization

3 participants