zod icon indicating copy to clipboard operation
zod copied to clipboard

Allow default values for empty strings

Open zomars opened this issue 1 year ago • 3 comments

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.

zomars avatar Aug 02 '22 19:08 zomars

Same issue here.

rcnespoli avatar Aug 04 '22 18:08 rcnespoli

A workaround is using a transform:

const stringWithDefault = z.string().optional().transform((val) => val || "tuna")
const result = stringWithDefault.parse("") // => returns "tuna"; 

zomars avatar Aug 04 '22 19:08 zomars

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'.

rcnespoli avatar Aug 04 '22 19:08 rcnespoli

@zomars approach would be the recommended way to do this

const stringWithDefault = z.string().optional().transform((val) => val || "tuna")

colinhacks avatar Sep 06 '22 08:09 colinhacks