Skip to content

Make nullable schemas referenced with $ref generate optional types - #931

Open
k-kohey wants to merge 3 commits into
apple:mainfrom
k-kohey:fix-nullable-referenced-response-body
Open

Make nullable schemas referenced with $ref generate optional types#931
k-kohey wants to merge 3 commits into
apple:mainfrom
k-kohey:fix-nullable-referenced-response-body

Conversation

@k-kohey

@k-kohey k-kohey commented Aug 5, 2026

Copy link
Copy Markdown

Motivation

When a response body schema is referenced with $ref, the generated type is not optional even if the referenced schema is nullable.

components:
  schemas:
    MyObject:
      type: [object, null]
      properties:
        id:
          type: string
      required:
        - id
  responses:
    MyResponse:
      description: OK
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/MyObject'

Current output:

@frozen public enum Body: Sendable, Hashable {
    case json(Components.Schemas.MyObject)
}

Expected output:

@frozen public enum Body: Sendable, Hashable {
    case json(Components.Schemas.MyObject?)
}

Writing the same schema inline already produces ...?, so the behavior differs depending on whether $ref is used. This also contradicts the documented rule in Handling-nullable-schemas.md: "The nullability of a schema is propagated through references."

Modifications

Removed the .reference branch in TypeAssigner.typeUsage(usingNamingHint:withSchema:components:inParent:), which resolved the type name without applying nullability. Every schema now goes through _typeUsage, which already applies withOptional(isOptional(...)) to references, so inline and referenced schemas share a single path.

Request bodies are unaffected, since translateRequestBody explicitly drops optionality with withOptional(false).

Result

Nullable schemas referenced with $ref are generated as optional types. This covers both type: [object, null] and nullable: true, as well as transitive references through another schema. The output for non-nullable references is unchanged.

Test Plan

Added tests to SnippetBasedReferenceTests.

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