Skip to content

ValueByDiscriminator() generates incorrect method call when union type is referenced via external ref in allOf #2470

Closed

Description

@alekgit
Description

When a schema is defined as allOf: [ExternalUnion, LocalObject] where ExternalUnion is a discriminated oneOf from another file, ValueByDiscriminator() is generated with incorrect syntax.

Reproduction

Spec structure (two files):

diff.yaml:

DiffFile:
  oneOf:
    - $ref: '#/components/schemas/GitDiffFile'
    - $ref: '#/components/schemas/AddedImageDiffFile'
  discriminator:
    propertyName: diff_type

pulls.yaml (references diff.yaml as external):

PRFile:
  allOf:
    - $ref: './diff.yaml#/components/schemas/DiffFile'
    - $ref: '#/components/schemas/ViewedStatus'

With import-mapping: {"./diff.yaml": "mypkg/diff"} in oapi-codegen config.

Generated code (broken)
func (t PRFile) ValueByDiscriminator() (interface{}, error) {
    discriminator, err := t.Discriminator()
    switch discriminator {
    case "GitDiffFile":
        return t.AsexternalRef0.GitDiffFile()  // ← compile error: undefined
    }
}
Expected
case "GitDiffFile":
    return t.AsExternalRef0GitDiffFile()  // matches the actually generated As* method
Root cause

In union.tmpl, ValueByDiscriminator() uses $type from $discriminator.Mapping directly:

return t.As{{$type}}()

For external refs, $type = "externalRef0.GitDiffFile" which produces invalid Go (t.AsexternalRef0.GitDiffFile()).

The As* / From* / Merge* methods correctly use {{ .Method }} from the union element, which produces ExternalRef0GitDiffFile. ValueByDiscriminator() should do the same.

Patch
--- a/pkg/codegen/templates/union.tmpl
+++ b/pkg/codegen/templates/union.tmpl
@@ -82,7 +82,9 @@ func (t {{.TypeName}}) ValueByDiscriminator() (interface{}, error) {
             switch discriminator{
                 {{range $value, $type := $discriminator.Mapping -}}
                     case "{{$value}}":
-                        return t.As{{$type}}()
+                        {{- range $el := .Schema.UnionElements -}}
+                        {{- if eq (print $el) $type}}return t.As{{$el.Method}}(){{end -}}
+                        {{- end}}
                 {{end -}}
                 default:
                     return nil, errors.New("unknown discriminator value: "+discriminator)
Version

oapi-codegen v2.7.0

Activity

  1. added 2 commits that reference this issue on Jul 16, 2026
    12ce1a8
    fdc6c6a
  2. added a commit that references this issue on Jul 16, 2026
    1457922
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions