Skip to content

Commit e6b2bad

Browse files
committed
Fix nullable + enum
1 parent 5b97fb8 commit e6b2bad

File tree

7 files changed

+283
-265
lines changed

7 files changed

+283
-265
lines changed

packages/openapi-typescript/examples/github-api-export-type-immutable.ts

+35-35
Large diffs are not rendered by default.

packages/openapi-typescript/examples/github-api-immutable.ts

+35-35
Large diffs are not rendered by default.

packages/openapi-typescript/examples/github-api.ts

+35-35
Large diffs are not rendered by default.

packages/openapi-typescript/examples/stripe-api.ts

+157-157
Large diffs are not rendered by default.

packages/openapi-typescript/src/transform/schema-object.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,11 @@ export function transformSchemaObjectWithComposition(
114114
options.ctx.injectFooter.push(enumType);
115115
return ts.factory.createTypeReferenceNode(enumType.name);
116116
}
117-
return tsUnion(schemaObject.enum.map(tsLiteral));
117+
const enumType = schemaObject.enum.map(tsLiteral);
118+
if ((Array.isArray(schemaObject.type) && schemaObject.type.includes("null")) || schemaObject.nullable) {
119+
enumType.push(NULL);
120+
}
121+
return tsUnion(enumType);
118122
}
119123

120124
/**

packages/openapi-typescript/test/transform/schema-object/composition.test.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ describe("composition", () => {
3838
type: ["string", "null"],
3939
enum: ["blue", "green", "yellow"],
4040
},
41-
want: '"blue" | "green" | "yellow"',
41+
want: '"blue" | "green" | "yellow" | null',
4242
// options: DEFAULT_OPTIONS,
4343
},
4444
],
@@ -49,7 +49,7 @@ describe("composition", () => {
4949
type: ["string", "null"],
5050
enum: ["", "blue", "green", "yellow"],
5151
},
52-
want: '"" | "blue" | "green" | "yellow"',
52+
want: '"" | "blue" | "green" | "yellow" | null',
5353
// options: DEFAULT_OPTIONS,
5454
},
5555
],

packages/openapi-typescript/test/transform/schema-object/string.test.ts

+14
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,20 @@ describe("transformSchemaObject > string", () => {
7777
// options: DEFAULT_OPTIONS,
7878
},
7979
],
80+
[
81+
"enum + nullable",
82+
{
83+
given: { type: ["string", "null"], enum: ["A", "B", "C"] },
84+
want: '"A" | "B" | "C" | null',
85+
},
86+
],
87+
[
88+
"enum + nullable (deprecated syntax)",
89+
{
90+
given: { type: "string", enum: ["A", "B", "C"], nullable: true },
91+
want: '"A" | "B" | "C" | null',
92+
},
93+
],
8094
];
8195

8296
for (const [testName, { given, want, options = DEFAULT_OPTIONS, ci }] of tests) {

0 commit comments

Comments
 (0)