You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Primitives in JS (TS) are compatible with a type which defines { toString: () => string }. However, if a Zod type is created using z.function() with no arguments, the generated types have an ...args parameter that prevent it from being used with primitives. (That is, primitives are not compatible with { toString: (...args: unknown[]) => string }.)
I believe if you call z.function() without providing an args() call, the produced matcher should not have an ...args parameter.
Hmm, this is interesting. Tbh, not sure if this can be done 😄
What do you want to achieve?
If you want to have some runtime validation that something has toString you can do something like
const toStringSchema = z.any().refine(
(val) => typeof val?.toString === "function",
{ message: "Value must have a toString method" }
);
This does not provide a type safety but it works.
What I'm looking to achieve is to make sure that the function provides a type definition with a function that takes no arguments, rather than a variable-length parameter array. I think it's a very unique use case, though—having to match the toString function is definitely a very rare requirement. 😅
I guess for this use case, I could just override the type definition to get what I need.
consttoStringSchema=z.any().refine((val)=>typeofval?.toString==="function",{message: "Value must have a toString method"});typeToString=Omit<z.infer<typeoftoStringSchema>,'toString'>&{toString: ()=>string};
Would be interesting to see if this could be done, though. Maybe with a different type, like z.function().noArgs()?
Summary
Primitives in JS (TS) are compatible with a type which defines
{ toString: () => string }
. However, if a Zod type is created usingz.function()
with no arguments, the generated types have an...args
parameter that prevent it from being used with primitives. (That is, primitives are not compatible with{ toString: (...args: unknown[]) => string }
.)I believe if you call
z.function()
without providing anargs()
call, the produced matcher should not have an...args
parameter.Details
If I do the following:
I get the following error from the final line:
ts: Type 'number' is not assignable to type '{ toString: (...args: unknown[]) => string; }'.
However, if I remove Zod from the picture and define a type manually which I would expect to be equivalent, it works:
This is because the defined type does not have an
...args
parameter.The text was updated successfully, but these errors were encountered: