Skip to content

Commit 326124b

Browse files
authored
support enum without a type field (astahmer#83)
* closes: astahmer#79 issue with singleton enum * closes: astahmer#82 support enum without type * closes: astahmer#82 support enum without type
1 parent 851ae9d commit 326124b

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

.changeset/cyan-tables-fetch.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"typed-openapi": patch
3+
---
4+
5+
closes: #82 by supporting enum without type

packages/typed-openapi/src/openapi-schema-to-ts.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,18 @@ export const openApiSchemaToTs = ({ schema, meta: _inheritedMeta, ctx }: Openapi
9494
if (schemaType === "number" || schemaType === "integer") return t.number();
9595
if (schemaType === "null") return t.literal("null");
9696
}
97+
if (!schemaType && schema.enum) {
98+
return t.union(schema.enum.map((value) => {
99+
if (typeof value === "string") {
100+
return t.literal(`"${value}"`)
101+
}
102+
if (value === null) {
103+
return t.literal("null")
104+
}
105+
// handle boolean and number literals
106+
return t.literal(value)
107+
}));
108+
}
97109

98110
if (schemaType === "array") {
99111
if (schema.items) {

packages/typed-openapi/tests/openapi-schema-to-ts.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,16 @@ test("getSchemaBox", () => {
365365
}
366366
`);
367367

368+
expect(getSchemaBox({ enum: ["red", "amber", "green", null, 42, true] })).toMatchInlineSnapshot(
369+
`
370+
{
371+
"type": "union",
372+
"value": "("red" | "amber" | "green" | null | 42 | true)",
373+
}
374+
`,
375+
);
376+
377+
368378
expect(getSchemaBox({
369379
"type": "object",
370380
"properties": {

0 commit comments

Comments
 (0)