Skip to content

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

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

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

Conversation

@jasperpatterson
Copy link
Copy Markdown
Contributor

@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 instanceOf type guards in typescript-fetch for discriminated unions so they validate discriminator values and work with name vs baseName (snake_case and dashed). Also updates oneOf encoding to use wire-format discriminator keys and tightens decoding and enum handling.

  • Bug Fixes
    • instanceOf: validate discriminator values for single-value enums (string or numeric); check both name and baseName for required fields when they differ (via hasSanitizedName) without duplicating checks when they match. Ensure hasSanitizedName is copied in ExtendedCodegenProperty.
    • ToJSONTyped: emit the discriminator using the wire-format key (propertyBaseName); keep numeric singleton enum literals unquoted.
    • FromJSONTyped: fix oneOf decoding and array type narrowing to avoid TS “every on never” errors and support enumUnknownDefaultCase. Do not flatten oneOf variant properties when an allOf item is a $ref to a oneOf schema without a discriminator.

Written for commit 2416c5b. 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.

@wing328
Copy link
Copy Markdown
Member

wing328 commented Apr 21, 2026

cc @TiFu (2017/07) @taxpon (2017/07) @sebastianhaas (2017/07) @kenisteward (2017/07) @Vrolijkx (2017/09) @macjohnny (2018/01) @topce (2018/10) @akehir (2019/07) @petejohansonxo (2019/11) @amakhrov (2020/02) @davidgamero (2022/03) @mkusaka (2022/04) @joscha (2024/10) @dennisameling (2026/02)

Copy link
Copy Markdown
Member

@macjohnny macjohnny left a comment

Choose a reason for hiding this comment

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

thanks for your contribution

{{#vars}}
{{#required}}
{{#hasSanitizedName}}
if ((!('{{name}}' in value) && !('{{baseName}}' in value)) || (value['{{name}}'] === undefined && value['{{baseName}}'] === undefined)) return false;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

shouldnt it be either name or baseName?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@macjohnny

instanceOf is called in both directions, so it needs to handle both casings:

  • Decoding in FromJSONTyped: called on raw JSON, where keys use baseName (e.g., discriminator-field)
  • Encoding in ToJSONTyped: called on the TS object, where keys use name (e.g., discriminatorField)

The {{#hasSanitizedName}} guard ensures we only emit the dual check when it's actually needed — for the common case where name === baseName, it falls back to the simpler single check.

I did consider making the function aware of direction but it felt too complex for not much gain, and would change the public instanceOf API.

@jasperpatterson jasperpatterson force-pushed the fix-instanceof-for-discriminated-unions branch from a333298 to 7fdd856 Compare May 6, 2026 20:33
…r-discriminated-unions

# Conflicts:
#	samples/client/petstore/typescript-fetch/builds/oneOf/apis/DefaultApi.ts
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.

3 participants