Z
Zod4mo ago
Whimsy

Whimsy - .optional() makes the type optional? l...

.optional() makes the type optional? like using it with z.boolean().default(false) makes it boolean | undefined
4 Replies
unnreaal
unnreaal4mo ago
you don't need to use .optional when using .default @Whimsy
Scott Trinh
Scott Trinh4mo ago
optional is like ?: T | undefined and default is like object destructuring with default. Note that "it" is different between the input type and output type for default since the input type is T | undefined and the output type is just T (which is the point of default)
Steve
Steve4mo ago
Yeah on the Output type that is. .optional() allows undefined to be inputted, and outputs undefined for that value. .default(value) allows undefined to be inputted, and outputs typeof value for that value. So z.boolean().default(false makes the input type boolean | undefined and the output type boolean while z.boolean.optional() makes both boolean | undefined. You can see that here: https://github.com/colinhacks/zod/blob/main/src/types.ts#L4637 https://github.com/colinhacks/zod/blob/main/src/types.ts#L4724 In the codebase it is even more explicitly stated: The output can never be undefined when using .default()
Whimsy
WhimsyOP3mo ago
yeah that's what i was asking
Want results from more Discord servers?
Add your server