zod
zod copied to clipboard
Allow default values for empty strings
I'm trying to assign a default value when string is empty without any luck.
import { z } from "zod";
const stringWithDefault = z.string().optional().default("tuna")
const result = stringWithDefault.parse(""); // => Should be "tuna" instead is ""
// ^ ?
console.log(result);
How could I achieve this?
const result = stringWithDefault.parse(undefined) // => returns "tuna";
const result = stringWithDefault.parse("") // => returns "";
Basically I want both cases to use the default value.
Same issue here.
A workaround is using a transform:
const stringWithDefault = z.string().optional().transform((val) => val || "tuna")
const result = stringWithDefault.parse("") // => returns "tuna";
Thanks. There is another issue related transform>
const stringToNumber = z.string().transform((val) => parseInt(val, 10))
const result = stringToNumber.parse("10") // Type 'string' is not assignable to type 'number'.
@zomars approach would be the recommended way to do this
const stringWithDefault = z.string().optional().transform((val) => val || "tuna")