unnreaal - tsconst schema = z.coerce.string()....
But
z.coerce.string()
will always cast the value to a string, why not just string
instead of string | undefined
?24 Replies
Infer is the input type.
z.output
gives the output typestill the same with
z.output
Oh yeah, I guess it would be that type. Optional doesn't make sense here since coerce swallows undefined. 🤔
its a type error
no?
Well... sure, I could see that, but really optional and nullable are just not really meaningful for coerce types.
Same for union, really
Is there something specific you're intending to mean by making it optional? It already accepts undefined as an input.
no, i mean that the type (
z.output
) is wrongIt's only wrong because
.optional
makes everything | undefined
, but optional
doesn't mean anything for z.coerce
schemas, so it's "right" but only technically right.yes bro, i know the
| undefined
doesn't mean anything for z.coerce
schemas
i mean that the type is completely wrongfor instance, this is also supported, but doesn't work:
In actuality, it's always
string
at runtime.I mean that
.optional
should not be an option for coerce schemas.but the
name
is always a string here
so zod should throw an error warning the optional can not (or is unnecessary) be used with coerce schemasNope: this is
{ name: string; }
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
it should just not allow you to
.optional()
on a coerce schema.nop
im sure it isnt
it is
{ name?: string | undefined; }
try yourselfno, your original (without the .optional) is
string
bro, i edited the message (before you send the playground link)
yep! don't use
optional
for coerce schemas.zod should throw an error
or at least warn users
yes
it should just not include an
.optional
method.
but it does for now, so just avoid it until we fix that..optional is in ZodType, no?
it is! we'll need to fix that.
in the meantime, do not:
1. Use
optional
, nullish
, or nullable
with z.coerce
schemas
2. Use z.coerce
schemas in a z.union
3. Probably other stuff.I filed an issue: https://github.com/colinhacks/zod/issues/3837
GitHub
We should not allow
optional
, nullish
, or nullable
on `z.coer...Since z.coerce.* schemas will always return the primitive, even if you pass undefined or null, we should disallow this. Also, things like z.union([z.coerce.string(), z.coerce.number()]) will always...