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 @@ -33,6 +33,14 @@ import { legalizeName } from "../JavaScript/utils.js";

import type { typeScriptZodOptions } from "./language.js";

type TypeScriptZodRendererOptions = Omit<
OptionValues<typeof typeScriptZodOptions>,
"preferConstValues"
> &
Partial<
Pick<OptionValues<typeof typeScriptZodOptions>, "preferConstValues">
>;

export class TypeScriptZodRenderer extends ConvenienceRenderer {
/** TypeRefs of object types that participate in a reference cycle.
* These must be emitted as z.lazy() schemas with an explicit type
Expand All @@ -42,7 +50,7 @@ export class TypeScriptZodRenderer extends ConvenienceRenderer {
public constructor(
targetLanguage: TargetLanguage,
renderContext: RenderContext,
protected readonly _options: OptionValues<typeof typeScriptZodOptions>,
protected readonly _options: TypeScriptZodRendererOptions,
) {
super(targetLanguage, renderContext);
}
Expand Down Expand Up @@ -315,13 +323,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 (this._options.preferConstValues && 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
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import { TypeScriptZodRenderer } from "./TypeScriptZodRenderer.js";

export const typeScriptZodOptions = {
justSchema: new BooleanOption("just-schema", "Schema only", false),
preferConstValues: new BooleanOption(
"prefer-const-values",
"Use literal schema for string enums with single value",
false,
),
};

export const typeScriptZodLanguageConfig = {
Expand All @@ -35,8 +40,8 @@ export class TypeScriptZodTargetLanguage extends TargetLanguage<
super(typeScriptZodLanguageConfig);
}

public getOptions(): Record<string, never> {
return {};
public getOptions(): typeof typeScriptZodOptions {
return typeScriptZodOptions;
}

public get stringTypeMapping(): StringTypeMapping {
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"]
}
4 changes: 3 additions & 1 deletion test/languages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2114,7 +2114,9 @@ export const TypeScriptZodLanguage: Language = {
"required-non-properties.schema",
],
rendererOptions: {},
quickTestRendererOptions: [],
quickTestRendererOptions: [
["single-value-enum.schema", { "prefer-const-values": "true" }],
],
sourceFiles: ["src/language/TypeScriptZod/index.ts"],
};

Expand Down
36 changes: 36 additions & 0 deletions test/unit/typescript-zod-const-enum.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { InputData, JSONSchemaInput, quicktype } from "quicktype-core";
import { expect, test } from "vitest";

async function render(preferConstValues: boolean): 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",
rendererOptions: { "prefer-const-values": preferConstValues },
});
return result.lines.join("\n");
}

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

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

test("TypeScript Zod emits an enum for a single-value enum by default", async () => {
expect(await render(false)).toContain("z.enum([");
});