diff --git a/.chronus/changes/fix-openapi3-nullable-union-variants-2026-9-19-21-28-16.md b/.chronus/changes/fix-openapi3-nullable-union-variants-2026-9-19-21-28-16.md new file mode 100644 index 00000000000..975c6be5130 --- /dev/null +++ b/.chronus/changes/fix-openapi3-nullable-union-variants-2026-9-19-21-28-16.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@typespec/openapi3" +--- + +Fix invalid OpenAPI 3.0 output for a union of several types with `null`, such as `string | int32 | null`. `nullable: true` is now set on each variant of the `anyOf` or `oneOf` instead of on the wrapper schema, where OpenAPI 3.0 ignores it because the wrapper has no `type`. diff --git a/packages/openapi3/src/schema-emitter-3-0.ts b/packages/openapi3/src/schema-emitter-3-0.ts index b8ae0826e0c..f1c7e03198e 100644 --- a/packages/openapi3/src/schema-emitter-3-0.ts +++ b/packages/openapi3/src/schema-emitter-3-0.ts @@ -200,7 +200,9 @@ export class OpenAPI3SchemaEmitter extends OpenAPI3SchemaEmitterBase { `, ); ok(res.isRef); - ok(res.schemas.Pet.properties.name.nullable); - deepStrictEqual(res.schemas.Pet.properties.name.anyOf, [ - { - type: "integer", - format: "int32", - }, - { - type: "string", - }, - ]); + deepStrictEqual(res.schemas.Pet.properties.name, { + anyOf: [ + { + type: "integer", + format: "int32", + nullable: true, + }, + { + type: "string", + nullable: true, + }, + ], + }); + }); + + it("sets nullable on each variant when literals and scalars are mixed", async () => { + const res = await oapiForModel( + "Pet", + ` + model Pet { + name: "a" | int32 | null; + }; + `, + ); + deepStrictEqual(res.schemas.Pet.properties.name, { + anyOf: [ + { type: "string", enum: ["a"], nullable: true }, + { type: "integer", format: "int32", nullable: true }, + ], + }); + }); + + it("sets nullable on each variant of a named union and keeps its doc on the union", async () => { + const openApi = await openApiFor(` + /** A name or a number. */ + union Test { string, int32, null } + `); + deepStrictEqual(openApi.components.schemas.Test, { + anyOf: [ + { type: "string", nullable: true }, + { type: "integer", format: "int32", nullable: true }, + ], + description: "A name or a number.", + }); + }); + + it("sets nullable on each variant of a @oneOf union", async () => { + const openApi = await openApiFor(` + model Foo { + @oneOf + bar: string | int32 | null; + } + `); + deepStrictEqual(openApi.components.schemas.Foo.properties.bar, { + oneOf: [ + { type: "string", nullable: true }, + { type: "integer", format: "int32", nullable: true }, + ], + }); }); it("defines enums with a nullable variant", async () => {