Convert a boolean-ish string Value into a boolean type with Zod

Nov 22, 2023

Convert a boolean-ish string Value into a boolean type with Zod

import { z } from "zod";

const booleanString = z
  .string()
  .refine((value) => value === "true" || value === "false", {
    message: "Value must be a boolean",
  })
  .transform((value) => value === "true");

console.log(booleanString.parse("true")); // true
console.log(typeof booleanString.parse("true")); // boolean

console.log(booleanString.parse("false")); // false
console.log(typeof booleanString.parse("false")); // boolean