Add `.with()`
An escape hatch API. Calling schema.with<T>() or schema.with(T) will return typeof schema & { _zod: T }. Basically a way to override any of the schemas internals, including:
Input & output types #4032
z.string().check(z.lowercase()).with<{ input: Lowercase<string>, output: Lowercase<string> }>
Brands: #4764
const USD = z.string().with<{
input: string & z.$brand<"USD">;
output: string & z.$brand<"USD">;
}>();
type USDIn = z.input<typeof USD>; // string & z.core.$brand<"USD">
type USDOut = z.output<typeof USD>; // string & z.core.$brand<"USD">
Statically known "tags" for versioning, etc. #4319
z.object({
name: z.string().with({ version: 2 }) // ZodString & $with<{ version: 2}> (also available at runtime in .def.with)
})
Subtypes: string & {}
Others:
- Named elements in tuple: https://github.com/colinhacks/zod/issues/4481
- Loose enum (
string & {}): https://github.com/colinhacks/zod/pull/4785/files
@colinhacks I think intersecting with a complex generic class instance leads to bad performance when TS measures variance. IIRC I had tried something similar years ago and ran into TS compiler performance problems before I settled on the approach of creating wrapper classes that extend ZodType (with Zod 3) to add custom fields because it has better performance.
The issue was something like, in many cases when comparing class instance types, TS can skip a deep structural comparison, but if any arbitrary properties are intersected on, it always has to do the complete deep comparison.
Hi, @colinhacks. I'm Dosu, and I'm helping the Zod team manage their backlog and am marking this issue as stale.
Issue Summary:
- You proposed a
.with()method for schemas to override internals like input/output types and metadata for advanced use cases. - A community member noted that intersecting with complex generic class instances can cause TypeScript compiler performance issues and suggested wrapper classes extending
ZodTypeas an alternative. - Another user expressed interest in contributing by submitting a PR for this feature.
- The issue remains unresolved with no recent updates or progress.
What's Next:
- Please let me know if this feature is still relevant for the latest version of Zod by commenting here to keep the discussion open.
- Otherwise, I will automatically close this issue in 7 days.
Thanks for your understanding and contribution!