Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -376,13 +376,26 @@ export class TypeScriptZodRenderer extends ConvenienceRenderer {
protected emitEnum(e: EnumType, enumName: Name): void {
this.ensureBlankLine();
this.emitDescription(this.descriptionForType(e));
this.emitLine("\nexport const ", enumName, "Schema = ", "z.enum([");
this.indent(() =>
this.forEachEnumCase(e, "none", (_, jsonName) => {
this.emitLine('"', stringEscape(jsonName), '",');
}),
);
this.emitLine("]);");

if (e.cases.size === 1) {
const value = e.cases.values().next().value;
if (value === undefined) panic("Single-value enum has no case.");
this.emitLine(
"\nexport const ",
enumName,
"Schema = z.literal(",
JSON.stringify(value),
");",
);
} else {
this.emitLine("\nexport const ", enumName, "Schema = ", "z.enum([");
this.indent(() =>
this.forEachEnumCase(e, "none", (_, jsonName) => {
this.emitLine('"', stringEscape(jsonName), '",');
}),
);
this.emitLine("]);");
}
if (!this._options.justSchema) {
this.emitLine(
"export type ",
Expand Down
3 changes: 3 additions & 0 deletions test/inputs/schema/single-value-enum.1.fail.enum.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"kind": "other"
}
3 changes: 3 additions & 0 deletions test/inputs/schema/single-value-enum.1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"kind": "only"
}
10 changes: 10 additions & 0 deletions test/inputs/schema/single-value-enum.schema
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"type": "object",
"properties": {
"kind": {
"type": "string",
"enum": ["only"]
}
},
"required": ["kind"]
}
31 changes: 31 additions & 0 deletions test/unit/typescript-zod-const-enum.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { InputData, JSONSchemaInput, quicktype } from "quicktype-core";
import { expect, test } from "vitest";

async function render(): Promise<string> {
const schemaInput = new JSONSchemaInput(undefined);
await schemaInput.addSource({
name: "TopLevel",
schema: JSON.stringify({
type: "object",
properties: {
kind: { type: "string", enum: ["only"] },
},
required: ["kind"],
}),
});
const inputData = new InputData();
inputData.addInput(schemaInput);

const result = await quicktype({
inputData,
lang: "typescript-zod",
});
return result.lines.join("\n");
}

test("TypeScript Zod emits a literal for a single-value enum", async () => {
const output = await render();

expect(output).toContain('z.literal("only")');
expect(output).not.toContain("z.enum([");
});
Loading