Skip to content

[typescript-fetch] Fix instanceOf type guards for discriminated unions#23497

Open
jasperpatterson wants to merge 3 commits intoOpenAPITools:masterfrom
jasperpatterson:fix-instanceof-for-discriminated-unions
Open

[typescript-fetch] Fix instanceOf type guards for discriminated unions#23497
jasperpatterson wants to merge 3 commits intoOpenAPITools:masterfrom
jasperpatterson:fix-instanceof-for-discriminated-unions

Conversation

@jasperpatterson
Copy link
Copy Markdown

@jasperpatterson jasperpatterson commented Apr 8, 2026

The generated instanceOf functions have two bugs:

  1. Discriminator value not checked: For oneOf unions where variants share the same discriminator field (e.g., type), instanceOf only checks field presence, not its value.

  2. Field name casing mismatch: instanceOf checks name (camelCase, e.g., someProperty) but when called on raw JSON in FromJSONTyped, the keys use baseName (original casing, e.g., some_property or some-property). This causes instanceOf to fail on raw JSON when name !== baseName.

Before

export function instanceOfOptionOne(value: object): value is OptionOne {
    if (!('discriminatorField' in value) || value['discriminatorField'] === undefined) return false;
    return true;
}

Both instanceOfOptionOne and instanceOfOptionTwo return true for { discriminatorField: 'optionTwo' }.

After

// When name === baseName (e.g., discriminatorField) — simple single check
export function instanceOfOptionOne(value: object): value is OptionOne {
    if (!('discriminatorField' in value) || value['discriminatorField'] === undefined) return false;
    if (value['discriminatorField'] !== 'optionOne') return false;
    return true;
}

// When name !== baseName (e.g., discriminatorField vs discriminator-field) — dual check
export function instanceOfDashedOptionOne(value: object): value is DashedOptionOne {
    if ((!('discriminatorField' in value) && !('discriminator-field' in value)) || (value['discriminatorField'] === undefined && value['discriminator-field'] === undefined)) return false;
    if (value['discriminatorField'] !== 'dashedOptionOne' && value['discriminator-field'] !== 'dashedOptionOne') return false;
    return true;
}

How it works

  • baseName fix: Each required field check now accepts either the TypeScript property name (name) or the original JSON property name (baseName). This is needed because instanceOf is called on both raw JSON (decoding) and converted TS objects (encoding). The template uses {{#hasSanitizedName}} to only emit the dual name/baseName check when the two actually differ, keeping the common case clean.
  • Discriminator value fix: For required enum properties with exactly one allowed value (i.e., discriminator fields on oneOf variants), an additional value check is generated.
  • ExtendedCodegenProperty fix: The hasSanitizedName flag (already computed by DefaultCodegen) was not being copied in ExtendedCodegenProperty's constructor, so the template conditional was always false. Added the missing copy.

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR solves a reported issue, reference it using GitHub's linking syntax (e.g., having "fixes #123" present in the PR description)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

Summary by cubic

Fixes incorrect instanceOf type guards in typescript-fetch for discriminated unions by validating discriminator values and supporting name vs baseName key casing. Guards now work reliably on both raw JSON and TS objects and avoid false positives.

  • Bug Fixes
    • For single-value enum discriminators, instanceOf now checks the field’s value, not just presence.
    • For required fields where name !== baseName, instanceOf accepts both keys and only emits dual checks when needed via hasSanitizedName.
    • Copies hasSanitizedName into ExtendedCodegenProperty so template conditionals execute correctly.
    • Adds tests for snake_case and dashed discriminators and regenerates samples.

Written for commit 389aa83. Summary will update on new commits.

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

2 issues found across 27 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache">

<violation number="1" location="modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache:40">
P2: Enum discriminator check always compares against a quoted literal, which breaks numeric/boolean singleton enums by forcing string comparison in instanceOf guards.</violation>
</file>

<file name="samples/client/petstore/typescript-fetch/builds/oneOf/models/TestDashedDiscriminatorResponse.ts">

<violation number="1" location="samples/client/petstore/typescript-fetch/builds/oneOf/models/TestDashedDiscriminatorResponse.ts:65">
P2: Serializer emits camelCase discriminatorField instead of dashed wire name, causing mismatch with FromJSON and model serializers.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

{{#-first}}
{{#-last}}
{{#hasSanitizedName}}
if (value['{{name}}'] !== '{{.}}' && value['{{baseName}}'] !== '{{.}}') return false;
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot Apr 8, 2026

Choose a reason for hiding this comment

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

P2: Enum discriminator check always compares against a quoted literal, which breaks numeric/boolean singleton enums by forcing string comparison in instanceOf guards.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache, line 40:

<comment>Enum discriminator check always compares against a quoted literal, which breaks numeric/boolean singleton enums by forcing string comparison in instanceOf guards.</comment>

<file context>
@@ -25,7 +25,28 @@ import { type {{modelName}}, {{modelName}}FromJSONTyped, {{modelName}}ToJSON, {{
+    {{#-first}}
+    {{#-last}}
+    {{#hasSanitizedName}}
+    if (value['{{name}}'] !== '{{.}}' && value['{{baseName}}'] !== '{{.}}') return false;
+    {{/hasSanitizedName}}
+    {{^hasSanitizedName}}
</file context>
Fix with Cubic

}
switch (value['discriminatorField']) {
case 'dashedOptionOne':
return Object.assign({}, DashedOptionOneToJSON(value), { discriminatorField: 'dashedOptionOne' } as const);
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot Apr 8, 2026

Choose a reason for hiding this comment

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

P2: Serializer emits camelCase discriminatorField instead of dashed wire name, causing mismatch with FromJSON and model serializers.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At samples/client/petstore/typescript-fetch/builds/oneOf/models/TestDashedDiscriminatorResponse.ts, line 65:

<comment>Serializer emits camelCase discriminatorField instead of dashed wire name, causing mismatch with FromJSON and model serializers.</comment>

<file context>
@@ -0,0 +1,72 @@
+    }
+    switch (value['discriminatorField']) {
+        case 'dashedOptionOne':
+            return Object.assign({}, DashedOptionOneToJSON(value), { discriminatorField: 'dashedOptionOne' } as const);
+        case 'dashedOptionTwo':
+            return Object.assign({}, DashedOptionTwoToJSON(value), { discriminatorField: 'dashedOptionTwo' } as const);
</file context>
Fix with Cubic

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.

1 participant