Skip to content

[TypeScript] Implement oneOf type resolution without discriminator#22201

Open
ksvirkou-hubspot wants to merge 17 commits intoOpenAPITools:masterfrom
ksvirkou-hubspot:feature/typestcriptOneOfAlgorithmWithoutDiscriminator
Open

[TypeScript] Implement oneOf type resolution without discriminator#22201
ksvirkou-hubspot wants to merge 17 commits intoOpenAPITools:masterfrom
ksvirkou-hubspot:feature/typestcriptOneOfAlgorithmWithoutDiscriminator

Conversation

@ksvirkou-hubspot
Copy link
Copy Markdown
Contributor

Summary

  • Implements oneOf type resolution for TypeScript generator when discriminator is not present
  • Adds OneOfClass with findMatchingType() method to determine correct type at runtime
  • Enhances ObjectSerializer to use type deduction when discriminator is unavailable
  • Includes comprehensive tests validating both discriminator and non-discriminator scenarios

Why

Previously, the TypeScript generator could only resolve oneOf types when a discriminator property was defined in the OpenAPI spec. This limitation meant that valid oneOf schemas without discriminators would fail at runtime.

This change enables automatic type resolution by checking which schema matches the provided data based on required fields, making the generated TypeScript clients more robust and easier to use for specs that don't define discriminators.

Implementation Details

  • Created OneOfClass base class with instanceOf() method to validate objects against schema requirements
  • Generated oneOf models now extend OneOfClass and include findMatchingType() to iterate through possible types
  • ObjectSerializer checks for findMatchingType() method when discriminator is undefined and uses it for type resolution
  • Falls back to original behavior if neither discriminator nor findMatchingType() is available
  • Throws descriptive error when type resolution is ambiguous (object matches multiple or no schemas)

Tests

Added integration tests at samples/openapi3/client/petstore/typescript/tests/one-of/:

  • Test spec: modules/openapi-generator/src/test/resources/3_0/typescript/oneOf.yaml defines two endpoints with oneOf responses
  • Without discriminator test: Validates that PetResponse (oneOf without discriminator) correctly deserializes to Cat based on required fields (name, petType)
  • With discriminator test: Validates that PetDiscriminatorResponse (oneOf with discriminator) correctly deserializes to Dog using discriminator property
  • Tests use Mocha + Chai with Nock for HTTP mocking
  • Run with: npm test in the test directory

Related issue: #19868

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.
    @TiFu @taxpon @sebastianhaas @kenisteward @Vrolijkx @macjohnny @topce @akehir @petejohansonxo @amakhrov @davidgamero @mkusaka @joscha

@ksvirkou-hubspot
Copy link
Copy Markdown
Contributor Author

The PR contains breaking change to generated TypeScript code, attributeTypeMap structure changed: Added required: boolean field to all model attribute type maps
- Before: Array<{name: string, baseName: string, type: string, format: string}>
- After: Array<{name: string, baseName: string, type: string, format: string, required: boolean}>
I can create method in model getRequiredFields() or create PR agains 8.0.0
Please check the PR and provide code review

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 the changes!

@ksvirkou-hubspot
Copy link
Copy Markdown
Contributor Author

Could you please check the PR again?
I've added significant changes.
Do I need to create a new PR against the 8.0 branch?
@macjohnny

@ksvirkou-hubspot
Copy link
Copy Markdown
Contributor Author

Any updates?
@macjohnny

@macjohnny
Copy link
Copy Markdown
Member

sorry for the delay, will try to find some time, its quite a complex PR

@ksvirkou-hubspot
Copy link
Copy Markdown
Contributor Author

Hi @macjohnny , just checking in on this PR.
Let me know if you need anything from me.
Thanks a lot for your time!

@ksvirkou-hubspot
Copy link
Copy Markdown
Contributor Author

Any updates?
@macjohnny

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.

@ksvirkou-hubspot I still didnt find time to thoroughly review this, but if you tested this thoroughly, i am fine merging that, just waiting for your confirmation.

are the tests of the samples/openapi3/client/petstore/typescript/tests/one-of/pom.xml correctly executed as part of the CI? i guess they would need to be configured somewhere here no? https://github.com/OpenAPITools/openapi-generator/tree/master/.github/workflows

return type.replace(" ", "").split("[|&<>]");
}

public class ExtendedCodegenModel extends CodegenModel {
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.

could we somehow do without an extended CodegenModel class? everytime the base class is updated (e.g. new properties are added), this would need to be updated here as well

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.

Alternatively, we could consider moving our additional properties to the base class itself.

I've extended the CodegenModel class because I need to add new properties specific to oneOf constructions. As far as I understand, extending the base class is a common approach — for example, the typescript-fetch generator uses the same pattern with its own ExtendedCodegenModel class.

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.

1 issue found across 1 file (changes from recent commits).

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=".github/workflows/samples-typescript-client.yaml">

<violation number="1" location=".github/workflows/samples-typescript-client.yaml:124">
P2: CI wiring for the new oneOf sample excludes the `tests/one-of` suite, so test-only changes won't trigger or run in this workflow.</violation>
</file>

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

- samples/openapi3/client/petstore/typescript/builds/browser/
#- samples/openapi3/client/petstore/typescript/tests/browser/
#- samples/openapi3/client/petstore/typescript/builds/nullable-enum/
- samples/openapi3/client/petstore/typescript/builds/one-of/
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot Mar 30, 2026

Choose a reason for hiding this comment

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

P2: CI wiring for the new oneOf sample excludes the tests/one-of suite, so test-only changes won't trigger or run in this workflow.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .github/workflows/samples-typescript-client.yaml, line 124:

<comment>CI wiring for the new oneOf sample excludes the `tests/one-of` suite, so test-only changes won't trigger or run in this workflow.</comment>

<file context>
@@ -119,6 +121,7 @@ jobs:
           - samples/openapi3/client/petstore/typescript/builds/browser/
           #- samples/openapi3/client/petstore/typescript/tests/browser/
           #- samples/openapi3/client/petstore/typescript/builds/nullable-enum/
+          - samples/openapi3/client/petstore/typescript/builds/one-of/
           - samples/client/petstore/typescript-fetch/builds/default/
           - samples/client/petstore/typescript-fetch/builds/es6-target/
</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.

2 participants