Aller au contenu
verdict:

Zod 4.3.0

notable

note: la synthèse et les notes de version sont en anglais

note: pas de synthèse pour cette release plus ancienne

Nous synthétisons les releases récentes. Les notes de version originales de cette version sont ci-dessous.

release-notesgithub.com/colinhacks/zod · 303 lignes
  1. This is Zod's biggest release since 4.0. It addresses several of Zod's longest-standing feature requests.
  2. ## `z.fromJSONSchema()`
  3. Convert JSON Schema to Zod ([#5534](https://github.com/colinhacks/zod/pull/5534), [#5586](https://github.com/colinhacks/zod/pull/5586))
  4. You can now convert JSON Schema definitions directly into Zod schemas. This function supports JSON Schema `"draft-2020-12"`, `"draft-7"`, `"draft-4"`, and OpenAPI 3.0.
  5. ```typescript
  6. import * as z from "zod";
  7. const schema = z.fromJSONSchema({
  8. type: "object",
  9. properties: {
  10. name: { type: "string", minLength: 1 },
  11. age: { type: "integer", minimum: 0 },
  12. },
  13. required: ["name"],
  14. });
  15. schema.parse({ name: "Alice", age: 30 }); // ✅
  16. ```
  17. The API should be considered experimental. There are no guarantees of 1:1 "round-trip soundness": `MySchema` > `z.toJSONSchema()` > `z.fromJSONSchema()`. There are several features of Zod that don't exist in JSON Schema and vice versa, which makes this virtually impossible.
  18. Features supported:
  19. - All primitive types (`string`, `number`, `integer`, `boolean`, `null`, `object`, `array`)
  20. - String formats (`email`, `uri`, `uuid`, `date-time`, `date`, `time`, `ipv4`, `ipv6`, and more)
  21. - Composition (`anyOf`, `oneOf`, `allOf`)
  22. - Object constraints (`additionalProperties`, `patternProperties`, `propertyNames`)
  23. - Array constraints (`prefixItems`, `items`, `minItems`, `maxItems`)
  24. - `$ref` for local references and circular schemas
  25. - Custom metadata is preserved
  26. ## `z.xor()` — exclusive union ([#5534](https://github.com/colinhacks/zod/pull/5534))
  27. A new exclusive union type that requires **exactly one** option to match. Unlike `z.union()` which passes if *any* option matches, `z.xor()` fails if zero or more than one option matches.
  28. ```typescript
  29. const schema = z.xor([z.string(), z.number()]);
  30. schema.parse("hello"); // ✅
  31. schema.parse(42); // ✅
  32. schema.parse(true); // ❌ zero matches
  33. ```
  34. When converted to JSON Schema, `z.xor()` produces `oneOf` instead of `anyOf`.
  35. ## `z.looseRecord()` — partial record validation ([#5534](https://github.com/colinhacks/zod/pull/5534))
  36. A new record variant that only validates keys matching the key schema, passing through non-matching keys unchanged. This is used to represent `patternProperties` in JSON Schema.
  37. ```typescript
  38. const schema = z.looseRecord(z.string().regex(/^S_/), z.string());
  39. schema.parse({ S_name: "John", other: 123 });
  40. // ✅ { S_name: "John", other: 123 }
  41. // only S_name is validated, "other" passes through
  42. ```
  43. ## `.exactOptional()` — strict optional properties ([#5589](https://github.com/colinhacks/zod/pull/5589))
  44. A new wrapper that makes a property *key-optional* (can be omitted) but does **not** accept `undefined` as an explicit value.
  45. ```typescript
  46. const schema = z.object({
  47. a: z.string().optional(), // accepts `undefined`
  48. b: z.string().exactOptional(), // does not accept `undefined`
  49. });
  50. schema.parse({}); // ✅
  51. schema.parse({ a: undefined }); // ✅
  52. schema.parse({ b: undefined }); // ❌
  53. ```
  54. This makes it possible to accurately represent the full spectrum of optionality expressible using [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig/exactOptionalPropertyTypes.html).
  55. ## `.apply()`
  56. A utility method for applying arbitrary transformations to a schema, enabling cleaner schema composition. ([#5463](https://github.com/colinhacks/zod/pull/5463))
  57. ```typescript
  58. const setCommonChecks = <T extends z.ZodNumber>(schema: T) => {
  59. return schema.min(0).max(100);
  60. };
  61. const schema = z.number().apply(setCommonChecks).nullable();
  62. ```
  63. ## `.brand()` cardinality
  64. The `.brand()` method now accepts a second argument to control whether the brand applies to input, output, or both. Closes [#4764](https://github.com/colinhacks/zod/issues/4764), [#4836](https://github.com/colinhacks/zod/issues/4836).
  65. ```typescript
  66. // output only (default)
  67. z.string().brand<"UserId">(); // output is branded (default)
  68. z.string().brand<"UserId", "out">(); // output is branded
  69. z.string().brand<"UserId", "in">(); // input is branded
  70. z.string().brand<"UserId", "inout">(); // both are branded
  71. ```
  72. ## Type predicates on `.refine()` ([#5575](https://github.com/colinhacks/zod/pull/5575))
  73. The `.refine()` method now supports type predicates to narrow the output type:
  74. ```typescript
  75. const schema = z.string().refine((s): s is "a" => s === "a");
  76. type Input = z.input<typeof schema>; // string
  77. type Output = z.output<typeof schema>; // "a"
  78. ```
  79. ## `ZodMap` methods: `min`, `max`, `nonempty`, `size` ([#5316](https://github.com/colinhacks/zod/pull/5316))
  80. `ZodMap` now has parity with `ZodSet` and `ZodArray`:
  81. ```typescript
  82. const schema = z.map(z.string(), z.number())
  83. .min(1)
  84. .max(10)
  85. .nonempty();
  86. schema.size; // access the size constraint
  87. ```
  88. ## `.with()` alias for `.check()` ([359c0db](https://github.com/colinhacks/zod/commit/359c0db6))
  89. A new `.with()` method has been added as a more readable alias for `.check()`. Over time, more APIs have been added that don't qualify as "checks". The new method provides a readable alternative that doesn't muddy semantics.
  90. ```typescript
  91. z.string().with(
  92. z.minLength(5),
  93. z.toLowerCase()
  94. );
  95. // equivalent to:
  96. z.string().check(
  97. z.minLength(5),
  98. z.trim(),
  99. z.toLowerCase()
  100. );
  101. ```
  102. ## `z.slugify()` transform
  103. Transform strings into URL-friendly slugs. Works great with `.with()`:
  104. ```typescript
  105. // Zod
  106. z.string().slugify().parse("Hello World"); // "hello-world"
  107. // Zod Mini
  108. // using .with() for explicit check composition
  109. z.string().with(z.slugify()).parse("Hello World"); // "hello-world"
  110. ```
  111. ## `z.meta()` and `z.describe()` in Zod Mini ([947b4eb](https://github.com/colinhacks/zod/commit/947b4eb2))
  112. Zod Mini now exports `z.meta()` and `z.describe()` as top-level functions for adding metadata to schemas:
  113. ```typescript
  114. import * as z from "zod/mini";
  115. // add description
  116. const schema = z.string().with(
  117. z.describe("A user's name"),
  118. );
  119. // add arbitrary metadata
  120. const schema2 = z.number().with(
  121. z.meta({ deprecated: true })
  122. );
  123. ```
  124. ## More ergonomic intersections https://github.com/colinhacks/zod/pull/5587
  125. When intersecting schemas that include `z.strictObject()`, Zod 4 now only rejects keys that are unrecognized by *both* sides of the intersection. Previously, any unrecognized key from either side would cause an error.
  126. This means keys that are recognized by at least one side of the intersection will now pass validation:
  127. ```ts
  128. const A = z.strictObject({ a: z.string() });
  129. const B = z.object({ b: z.string() });
  130. const C = z.intersection(A, B);
  131. // Keys recognized by either side now work
  132. C.parse({ a: "foo", b: "bar" }); // ✅ { a: "foo", b: "bar" }
  133. // Extra keys are stripped (follows strip behavior from B)
  134. C.parse({ a: "foo", b: "bar", c: "extra" }); // ✅ { a: "foo", b: "bar" }
  135. ```
  136. When both sides are strict, only keys unrecognized by *both* sides will error:
  137. ```ts
  138. const A = z.strictObject({ a: z.string() });
  139. const B = z.strictObject({ b: z.string() });
  140. const C = z.intersection(A, B);
  141. // Keys recognized by either side work
  142. C.parse({ a: "foo", b: "bar" }); // ✅
  143. // Keys unrecognized by BOTH sides error
  144. C.parse({ a: "foo", b: "bar", c: "extra" });
  145. // ❌ ZodError: Unrecognized key: "c"
  146. ```
  147. ## New locales
  148. - Armenian (`am`) ([#5531](https://github.com/colinhacks/zod/pull/5531))
  149. - Uzbek (`uz`) ([#5519](https://github.com/colinhacks/zod/pull/5519))
  150. ```ts
  151. import * as z from "zod";
  152. import { uz } from "zod/locales";
  153. z.config(uz());
  154. ```
  155. <br/><br/><br/>
  156. ## Bug fixes
  157. All of these changes fix soundness issues in Zod. As with any bug fix there's some chance of breakage if you were intentionally or unintentionally relying on this unsound behavior.
  158. ### ⚠️ `.pick()` and `.omit()` disallowed on object schemas containing refinements ([#5317](https://github.com/colinhacks/zod/pull/5317))
  159. Using `.pick()` or `.omit()` on object schemas with refinements now throws an error. Previously, this would silently drop the refinements, leading to unexpected behavior.
  160. ```typescript
  161. const schema = z.object({
  162. password: z.string(),
  163. confirmPassword: z.string(),
  164. }).refine(data => data.password === data.confirmPassword);
  165. schema.pick({ password: true });
  166. // 4.2: refinement silently dropped ⚠️
  167. // 4.3: throws error ❌
  168. ```
  169. **Migration**: The easiest way to migrate is to create a new schema using the `shape` of the old one.
  170. ```ts
  171. const newSchema = z.object(schema.shape).pick({ ... })
  172. ```
  173. ### ⚠️ overwriting properties with`.extend()` disallowed on object schemas with refinements ([#5317](https://github.com/colinhacks/zod/pull/5317))
  174. Similarly, `.extend()` will throws on schemas with refinements *if* you are overwriting existing properties.
  175. ```typescript
  176. const schema = z.object({
  177. a: z.string()
  178. }).refine(/* ... */);
  179. schema.extend({ a: z.number() }); // 4.3: throws error ❌
  180. ```
  181. Instead you can use `.safeExtend()`, which statically ensures that you aren't changing the type signature of any pre-existing properties.
  182. ```typescript
  183. const schema = z.object({
  184. a: z.string(),
  185. }).refine(/* ... */);
  186. schema.safeExtend({
  187. a: z.string().min(5).max(10)
  188. }); // ✅ allows overwrite, preserves refinement
  189. ```
  190. ### ⚠️ Stricter object masking methods ([#5581](https://github.com/colinhacks/zod/pull/5581))
  191. Object masking methods (`.pick()`, `.omit()`) now validate that the keys provided actually exist in the schema:
  192. ```typescript
  193. const schema = z.object({ a: z.string() });
  194. // 4.3: throws error for unrecognized keys
  195. schema.pick({ nonexistent: true });
  196. // error: unrecognized key: "nonexistent"
  197. ```
  198. <br/><br/><br/>
  199. ## Additional changes
  200. - Fixed JSON Schema generation for `z.iso.time` with minute precision ([#5557](https://github.com/colinhacks/zod/pull/5557))
  201. - Fixed error details for tuples with extraneous elements ([#5555](https://github.com/colinhacks/zod/pull/5555))
  202. - Fixed `includes` method params typing to accept `string | $ZodCheckIncludesParams` ([#5556](https://github.com/colinhacks/zod/pull/5556))
  203. - Fixed numeric formats error messages to be inclusive ([#5485](https://github.com/colinhacks/zod/pull/5485))
  204. - Fixed `implementAsync` inferred type to always be a promise ([#5476](https://github.com/colinhacks/zod/pull/5476))
  205. - Tightened E.164 regex to require a non-zero leading digit and 7–15 digits total ([#5524](https://github.com/colinhacks/zod/pull/5524))
  206. - Fixed Dutch (nl) error strings ([#5529](https://github.com/colinhacks/zod/pull/5529))
  207. - Convert `Date` instances to numbers in `minimum`/`maximum` checks ([#5351](https://github.com/colinhacks/zod/pull/5351))
  208. - Improved numeric keys handling in `z.record()` ([#5585](https://github.com/colinhacks/zod/pull/5585))
  209. - Lazy initialization of `~standard` schema property ([#5363](https://github.com/colinhacks/zod/pull/5363))
  210. - Functions marked as `@__NO_SIDE_EFFECTS__` for better tree-shaking ([#5475](https://github.com/colinhacks/zod/pull/5475))
  211. - Improved metadata tracking across child-parent relationships ([#5578](https://github.com/colinhacks/zod/pull/5578))
  212. - Improved locale translation approach ([#5584](https://github.com/colinhacks/zod/pull/5584))
  213. - Dropped id uniqueness enforcement at registry level ([#5574](https://github.com/colinhacks/zod/pull/5574))

voir sur githubimported 2026-09-28 via npm