Skip to content

Commit 151d47a

Browse files
authored
fix: Support for nullable enums (#146)
1 parent 865fcf6 commit 151d47a

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

plugins/typescript/src/core/schemaToTypeAliasDeclaration.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,18 @@ describe("schemaToTypeAliasDeclaration", () => {
6969
);
7070
});
7171

72+
it("should generate nullable enums (strings)", () => {
73+
const schema: SchemaObject = {
74+
type: "string",
75+
enum: ["foo", "bar", "baz"],
76+
nullable: true,
77+
};
78+
79+
expect(printSchema(schema)).toBe(
80+
`export type Test = "foo" | "bar" | "baz" | null;`
81+
);
82+
});
83+
7284
it("should generate enums (numbers)", () => {
7385
const schema: SchemaObject = {
7486
type: "integer",

plugins/typescript/src/core/schemaToTypeAliasDeclaration.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,8 @@ export const getType = (
126126
}
127127

128128
if (schema.enum) {
129-
return f.createUnionTypeNode(
130-
schema.enum.map((value) => {
129+
return f.createUnionTypeNode([
130+
...schema.enum.map((value) => {
131131
if (typeof value === "string") {
132132
return f.createLiteralTypeNode(f.createStringLiteral(value));
133133
}
@@ -140,8 +140,9 @@ export const getType = (
140140
);
141141
}
142142
return f.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword);
143-
})
144-
);
143+
}),
144+
...(schema.nullable ? [f.createLiteralTypeNode(f.createNull())] : []),
145+
]);
145146
}
146147

147148
// Handle implicit object

0 commit comments

Comments
 (0)