Skip to content
Sarj Code Standards

prefer-zod-enum-validator

Express closed string validators with a reusable Zod enum schema.

Why

Handwritten membership branches and parallel literal types repeat the accepted values and can drift. A named enum schema supplies validation and its inferred TypeScript union.

Fix

Declare a module-level Schema = z.enum([…]), derive its type with z.infer<typeof Schema>, and use Schema.parse(value) or Schema.safeParse(value).success. Preserve any intentional error, fallback, or protocol behavior when migrating.

Examples

Before — flagged Replace a closed handwritten string parser
src/status.ts
type Status = "ran" | "failed";
function status(value: unknown): Status {
if (value === "ran" || value === "failed") return value;
throw new Error("Invalid status");
}
After — preferred Define validation and the type from one enum
src/status.ts
import { z } from "zod";
const StatusSchema = z.enum(["ran", "failed"]);
type Status = z.infer<typeof StatusSchema>;
function status(value: unknown): Status {
return StatusSchema.parse(value);
}

References