zod 3.16.0 → 3.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +196 -183
- package/lib/index.mjs +11 -5
- package/lib/index.umd.js +11 -5
- package/lib/types.d.ts +3 -3
- package/lib/types.js +11 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="logo.svg" width="200px" align="center" />
|
|
2
|
+
<img src="logo.svg" width="200px" align="center" alt="Zod logo" />
|
|
3
3
|
<h1 align="center">Zod</h1>
|
|
4
|
+
<p align="center">
|
|
5
|
+
✨ <a href="https://zod.dev">https://zod.dev</a> ✨
|
|
6
|
+
<br/>
|
|
7
|
+
TypeScript-first schema validation with static type inference
|
|
8
|
+
</p>
|
|
4
9
|
</p>
|
|
10
|
+
<br/>
|
|
5
11
|
<p align="center">
|
|
6
12
|
<a href="https://github.com/colinhacks/zod/actions?query=branch%3Amaster"><img src="https://github.com/colinhacks/zod/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Zod CI status" /></a>
|
|
7
13
|
<a href="https://twitter.com/colinhacks" rel="nofollow"><img src="https://img.shields.io/badge/created%20by-@colinhacks-4BBAAB.svg" alt="Created by Colin McDonnell"></a>
|
|
@@ -12,6 +18,8 @@
|
|
|
12
18
|
</p>
|
|
13
19
|
|
|
14
20
|
<div align="center">
|
|
21
|
+
<a href="https://zod.dev">Documentation</a>
|
|
22
|
+
<span> • </span>
|
|
15
23
|
<a href="https://discord.gg/RcG33DQJdf">Discord</a>
|
|
16
24
|
<span> • </span>
|
|
17
25
|
<a href="https://www.npmjs.com/package/zod">NPM</a>
|
|
@@ -24,61 +32,62 @@
|
|
|
24
32
|
<br />
|
|
25
33
|
</div>
|
|
26
34
|
|
|
35
|
+
<br/>
|
|
27
36
|
<br/>
|
|
28
37
|
|
|
29
|
-
These docs have been translated into [Chinese](./README_ZH.md).
|
|
38
|
+
> These docs have been translated into [Chinese](./README_ZH.md).
|
|
30
39
|
|
|
31
|
-
|
|
40
|
+
## Table of contents
|
|
32
41
|
|
|
33
42
|
<!-- The full documentation is available both on the [official documentation site](https://zod.js.org/) (recommended) and in `README.md`.
|
|
34
43
|
|
|
35
|
-
|
|
44
|
+
#### Go to [zod.js.org](https://zod.js.org) >> -->
|
|
36
45
|
|
|
37
|
-
- [
|
|
46
|
+
- [Introduction](#introduction)
|
|
47
|
+
- [Sponsors](#sponsors)
|
|
48
|
+
- [Ecosystem](#ecosystem)
|
|
38
49
|
- [Installation](#installation)
|
|
39
|
-
- [Ecosystem](#ecosystem)
|
|
40
50
|
- [Basic usage](#basic-usage)
|
|
41
|
-
- [
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
- [
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
- [
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
- [
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
- [Schema methods](#zodtype-methods-and-properties)
|
|
51
|
+
- [Primitives](#primitives)
|
|
52
|
+
- [Literals](#literals)
|
|
53
|
+
- [Strings](#strings)
|
|
54
|
+
- [Numbers](#numbers)
|
|
55
|
+
- [NaNs](#nans)
|
|
56
|
+
- [Booleans](#booleans)
|
|
57
|
+
- [Dates](#dates)
|
|
58
|
+
- [Zod enums](#zod-enums)
|
|
59
|
+
- [Native enums](#native-enums)
|
|
60
|
+
- [Optionals](#optionals)
|
|
61
|
+
- [Nullables](#nullables)
|
|
62
|
+
- [Objects](#objects)
|
|
63
|
+
- [.shape](#shape)
|
|
64
|
+
- [.extend](#extend)
|
|
65
|
+
- [.merge](#merge)
|
|
66
|
+
- [.pick/.omit](#pickomit)
|
|
67
|
+
- [.partial](#partial)
|
|
68
|
+
- [.deepPartial](#deepPartial)
|
|
69
|
+
- [.passthrough](#passthrough)
|
|
70
|
+
- [.strict](#strict)
|
|
71
|
+
- [.strip](#strip)
|
|
72
|
+
- [.catchall](#catchall)
|
|
73
|
+
- [Arrays](#arrays)
|
|
74
|
+
- [.element](#element)
|
|
75
|
+
- [.nonempty](#nonempty)
|
|
76
|
+
- [.min/.max/.length](#minmaxlength)
|
|
77
|
+
- [Tuples](#tuples)
|
|
78
|
+
- [Unions](#unions)
|
|
79
|
+
- [Discriminated Unions](#discriminated-unions)
|
|
80
|
+
- [Records](#records)
|
|
81
|
+
- [Maps](#maps)
|
|
82
|
+
- [Sets](#sets)
|
|
83
|
+
- [Recursive types](#recursive-types)
|
|
84
|
+
- [JSON type](#json-type)
|
|
85
|
+
- [Cyclical data](#cyclical-objects)
|
|
86
|
+
- [Promises](#promises)
|
|
87
|
+
- [Instanceof](#instanceof)
|
|
88
|
+
- [Function schemas](#function-schemas)
|
|
89
|
+
- [Preprocess](#preprocess)
|
|
90
|
+
- [Schema methods](#schema-methods)
|
|
82
91
|
- [.parse](#parse)
|
|
83
92
|
- [.parseAsync](#parseasync)
|
|
84
93
|
- [.safeParse](#safeparse)
|
|
@@ -98,6 +107,7 @@ These docs have been translated into [Chinese](./README_ZH.md).
|
|
|
98
107
|
- [Type inference](#type-inference)
|
|
99
108
|
- [Writing generic functions](#writing-generic-functions)
|
|
100
109
|
- [Error handling](#error-handling)
|
|
110
|
+
- [Error formatting](#error-formatting)
|
|
101
111
|
- [Comparison](#comparison)
|
|
102
112
|
- [Joi](#joi)
|
|
103
113
|
- [Yup](#yup)
|
|
@@ -107,7 +117,7 @@ These docs have been translated into [Chinese](./README_ZH.md).
|
|
|
107
117
|
|
|
108
118
|
<!-- **Zod 2 is coming! Follow [@colinhacks](https://twitter.com/colinhacks) to stay updated and discuss the future of Zod.** -->
|
|
109
119
|
|
|
110
|
-
|
|
120
|
+
## Introduction
|
|
111
121
|
|
|
112
122
|
Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple `string` to a complex nested object.
|
|
113
123
|
|
|
@@ -123,17 +133,17 @@ Some other great aspects:
|
|
|
123
133
|
- Functional approach: [parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/)
|
|
124
134
|
- Works with plain JavaScript too! You don't need to use TypeScript.
|
|
125
135
|
|
|
126
|
-
|
|
136
|
+
### Sponsors
|
|
127
137
|
|
|
128
138
|
Sponsorship at any level is appreciated and encouraged. For individual developers, consider the [Cup of Coffee tier](https://github.com/sponsors/colinhacks). If you built a paid product using Zod, consider one of the [podium tiers](https://github.com/sponsors/colinhacks).
|
|
129
139
|
|
|
130
|
-
|
|
140
|
+
#### Gold
|
|
131
141
|
|
|
132
142
|
<table>
|
|
133
143
|
<tr>
|
|
134
144
|
<td align="center">
|
|
135
145
|
<a href="https://astro.build/">
|
|
136
|
-
<img src="https://avatars.githubusercontent.com/u/44914786?s=200&v=4" width="200px;" alt="" />
|
|
146
|
+
<img src="https://avatars.githubusercontent.com/u/44914786?s=200&v=4" width="200px;" alt="Astro" />
|
|
137
147
|
</a>
|
|
138
148
|
<br />
|
|
139
149
|
<b>Astro</b>
|
|
@@ -173,7 +183,7 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
|
|
|
173
183
|
</tr>
|
|
174
184
|
</table>
|
|
175
185
|
|
|
176
|
-
|
|
186
|
+
#### Silver
|
|
177
187
|
|
|
178
188
|
<table>
|
|
179
189
|
<tr>
|
|
@@ -205,7 +215,7 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
|
|
|
205
215
|
</tr>
|
|
206
216
|
</table>
|
|
207
217
|
|
|
208
|
-
|
|
218
|
+
#### Bronze
|
|
209
219
|
|
|
210
220
|
<table>
|
|
211
221
|
<tr>
|
|
@@ -242,34 +252,7 @@ Sponsorship at any level is appreciated and encouraged. For individual developer
|
|
|
242
252
|
</tr>
|
|
243
253
|
</table>
|
|
244
254
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
To install Zod v3:
|
|
248
|
-
|
|
249
|
-
```sh
|
|
250
|
-
npm install zod
|
|
251
|
-
```
|
|
252
|
-
|
|
253
|
-
⚠️ IMPORTANT: You must enable `strict` mode in your `tsconfig.json`. This is a best practice for all TypeScript projects.
|
|
254
|
-
|
|
255
|
-
```ts
|
|
256
|
-
// tsconfig.json
|
|
257
|
-
{
|
|
258
|
-
// ...
|
|
259
|
-
"compilerOptions": {
|
|
260
|
-
// ...
|
|
261
|
-
"strict": true
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
```
|
|
265
|
-
|
|
266
|
-
#### TypeScript requirements
|
|
267
|
-
|
|
268
|
-
- Zod 3.x requires TypeScript 4.1+
|
|
269
|
-
- Zod 2.x requires TypeScript 3.7+
|
|
270
|
-
- Zod 1.x requires TypeScript 3.3+
|
|
271
|
-
|
|
272
|
-
# Ecosystem
|
|
255
|
+
### Ecosystem
|
|
273
256
|
|
|
274
257
|
There are a growing number of tools that are built atop or support Zod natively! If you've built a tool or library on top of Zod, tell me about it [on Twitter](https://twitter.com/colinhacks) or [start a Discussion](https://github.com/colinhacks/zod/discussions). I'll add it below and tweet it out.
|
|
275
258
|
|
|
@@ -284,8 +267,8 @@ There are a growing number of tools that are built atop or support Zod natively!
|
|
|
284
267
|
- [`zod-endpoints`](https://github.com/flock-community/zod-endpoints): Contract-first strictly typed endpoints with Zod. OpenAPI compatible.
|
|
285
268
|
- [`express-zod-api`](https://github.com/RobinTail/express-zod-api): Build Express-based APIs with I/O schema validation and custom middlewares.
|
|
286
269
|
- [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema): Convert your Zod schemas into [JSON Schemas](https://json-schema.org/).
|
|
287
|
-
- [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod): Convert your [JSON Schemas](https://json-schema.org/) into Zod schemas.
|
|
288
|
-
- [`json-to-zod`](https://github.com/rsinohara/json-to-zod): Convert JSON objects into Zod schemas.
|
|
270
|
+
- [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod): Convert your [JSON Schemas](https://json-schema.org/) into Zod schemas. [Live demo](https://StefanTerdell.github.io/json-schema-to-zod-react/).
|
|
271
|
+
- [`json-to-zod`](https://github.com/rsinohara/json-to-zod): Convert JSON objects into Zod schemas. [Live demo](https://rsinohara.github.io/json-to-zod-react/).
|
|
289
272
|
- [`zod-dto`](https://github.com/kbkk/abitia/tree/master/packages/zod-dto): Generate Nest.js DTOs from a Zod schema.
|
|
290
273
|
- [`soly`](https://github.com/mdbetancourt/soly): Create CLI applications with zod.
|
|
291
274
|
- [`graphql-codegen-typescript-validation-schema`](https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema): GraphQL Code Generator plugin to generate form validation schema from your GraphQL schema
|
|
@@ -297,13 +280,40 @@ There are a growing number of tools that are built atop or support Zod natively!
|
|
|
297
280
|
- [`prisma-trpc-generator`](https://github.com/omar-dulaimi/prisma-trpc-generator): Emit fully implemented tRPC routers and their validation schemas using Zod.
|
|
298
281
|
- [`nestjs-graphql-zod`](https://github.com/incetarik/nestjs-graphql-zod): Generates NestJS GraphQL model classes from Zod schemas dynamically and provides GraphQL method decorators working with Zod schemas.
|
|
299
282
|
|
|
300
|
-
|
|
283
|
+
#### Form integrations
|
|
301
284
|
|
|
302
285
|
- [`react-hook-form`](https://github.com/react-hook-form/resolvers#zod): A first-party Zod resolver for React Hook Form
|
|
303
286
|
- [`zod-formik-adapter`](https://github.com/robertLichtnow/zod-formik-adapter): A community-maintained Formik adapter for Zod
|
|
304
287
|
- [`react-zorm`](https://github.com/esamattis/react-zorm): Standalone `<form>` generation and validation for React using Zod
|
|
305
288
|
|
|
306
|
-
|
|
289
|
+
## Installation
|
|
290
|
+
|
|
291
|
+
To install Zod v3:
|
|
292
|
+
|
|
293
|
+
```sh
|
|
294
|
+
npm install zod
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
⚠️ IMPORTANT: You must enable `strict` mode in your `tsconfig.json`. This is a best practice for all TypeScript projects.
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
// tsconfig.json
|
|
301
|
+
{
|
|
302
|
+
// ...
|
|
303
|
+
"compilerOptions": {
|
|
304
|
+
// ...
|
|
305
|
+
"strict": true
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
> **TypeScript requirements**
|
|
311
|
+
>
|
|
312
|
+
> - Zod 3.x requires TypeScript 4.1+
|
|
313
|
+
> - Zod 2.x requires TypeScript 3.7+
|
|
314
|
+
> - Zod 1.x requires TypeScript 3.3+
|
|
315
|
+
|
|
316
|
+
## Basic usage
|
|
307
317
|
|
|
308
318
|
Creating a simple string schema
|
|
309
319
|
|
|
@@ -338,8 +348,6 @@ type User = z.infer<typeof User>;
|
|
|
338
348
|
// { username: string }
|
|
339
349
|
```
|
|
340
350
|
|
|
341
|
-
# Defining schemas
|
|
342
|
-
|
|
343
351
|
## Primitives
|
|
344
352
|
|
|
345
353
|
```ts
|
|
@@ -403,9 +411,7 @@ z.string().nonempty({ message: "Can't be empty" });
|
|
|
403
411
|
|
|
404
412
|
> Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of other useful string validation functions.
|
|
405
413
|
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
You can customize certain errors when creating a string schema.
|
|
414
|
+
You can customize some common errors messages when creating a string schema.
|
|
409
415
|
|
|
410
416
|
```ts
|
|
411
417
|
const name = z.string({
|
|
@@ -551,7 +557,7 @@ FishEnum.options; // ["Salmon", "Tuna", "Trout"]);
|
|
|
551
557
|
|
|
552
558
|
## Native enums
|
|
553
559
|
|
|
554
|
-
Zod enums are the recommended approach to defining and validating enums. But if you need to validate against an enum from a third-party library (or you don't want to rewrite your existing enums) you can use `z.nativeEnum()
|
|
560
|
+
Zod enums are the recommended approach to defining and validating enums. But if you need to validate against an enum from a third-party library (or you don't want to rewrite your existing enums) you can use `z.nativeEnum()`.
|
|
555
561
|
|
|
556
562
|
**Numeric enums**
|
|
557
563
|
|
|
@@ -619,7 +625,7 @@ FruitEnum.enum.Apple; // "apple"
|
|
|
619
625
|
|
|
620
626
|
## Optionals
|
|
621
627
|
|
|
622
|
-
You can make any schema optional with `z.optional()
|
|
628
|
+
You can make any schema optional with `z.optional()`. This wraps the schema in a `ZodOptional` instance and returns the result.
|
|
623
629
|
|
|
624
630
|
```ts
|
|
625
631
|
const schema = z.optional(z.string());
|
|
@@ -628,7 +634,7 @@ schema.parse(undefined); // => returns undefined
|
|
|
628
634
|
type A = z.infer<typeof schema>; // string | undefined
|
|
629
635
|
```
|
|
630
636
|
|
|
631
|
-
|
|
637
|
+
For convenience, you can also call the `.optional()` method on an existing schema.
|
|
632
638
|
|
|
633
639
|
```ts
|
|
634
640
|
const user = z.object({
|
|
@@ -637,7 +643,7 @@ const user = z.object({
|
|
|
637
643
|
type C = z.infer<typeof user>; // { username?: string | undefined };
|
|
638
644
|
```
|
|
639
645
|
|
|
640
|
-
|
|
646
|
+
You can extract the wrapped schema from a `ZodOptional` instance with `.unwrap()`.
|
|
641
647
|
|
|
642
648
|
```ts
|
|
643
649
|
const stringSchema = z.string();
|
|
@@ -647,7 +653,7 @@ optionalString.unwrap() === stringSchema; // true
|
|
|
647
653
|
|
|
648
654
|
## Nullables
|
|
649
655
|
|
|
650
|
-
Similarly, you can create nullable types
|
|
656
|
+
Similarly, you can create nullable types with `z.nullable()`.
|
|
651
657
|
|
|
652
658
|
```ts
|
|
653
659
|
const nullableString = z.nullable(z.string());
|
|
@@ -655,14 +661,14 @@ nullableString.parse("asdf"); // => "asdf"
|
|
|
655
661
|
nullableString.parse(null); // => null
|
|
656
662
|
```
|
|
657
663
|
|
|
658
|
-
|
|
664
|
+
Or use the `.nullable()` method.
|
|
659
665
|
|
|
660
666
|
```ts
|
|
661
667
|
const E = z.string().nullable(); // equivalent to D
|
|
662
668
|
type E = z.infer<typeof E>; // string | null
|
|
663
669
|
```
|
|
664
670
|
|
|
665
|
-
|
|
671
|
+
Extract the inner schema with `.unwrap()`.
|
|
666
672
|
|
|
667
673
|
```ts
|
|
668
674
|
const stringSchema = z.string();
|
|
@@ -818,7 +824,7 @@ const deepPartialUser = user.deepPartial();
|
|
|
818
824
|
|
|
819
825
|
> Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples.
|
|
820
826
|
|
|
821
|
-
|
|
827
|
+
### `.passthrough`
|
|
822
828
|
|
|
823
829
|
By default Zod objects schemas strip out unrecognized keys during parsing.
|
|
824
830
|
|
|
@@ -835,8 +841,6 @@ person.parse({
|
|
|
835
841
|
// extraKey has been stripped
|
|
836
842
|
```
|
|
837
843
|
|
|
838
|
-
### `.passthrough`
|
|
839
|
-
|
|
840
844
|
Instead, if you want to pass through unknown keys, use `.passthrough()` .
|
|
841
845
|
|
|
842
846
|
```ts
|
|
@@ -849,7 +853,7 @@ person.passthrough().parse({
|
|
|
849
853
|
|
|
850
854
|
### `.strict`
|
|
851
855
|
|
|
852
|
-
You can _disallow_ unknown keys with `.strict()` . If there are any unknown keys in the input, Zod will throw an error.
|
|
856
|
+
By default Zod objects schemas strip out unrecognized keys during parsing. You can _disallow_ unknown keys with `.strict()` . If there are any unknown keys in the input, Zod will throw an error.
|
|
853
857
|
|
|
854
858
|
```ts
|
|
855
859
|
const person = z
|
|
@@ -986,7 +990,7 @@ For convenience, you can also use the `.or` method:
|
|
|
986
990
|
const stringOrNumber = z.string().or(z.number());
|
|
987
991
|
```
|
|
988
992
|
|
|
989
|
-
|
|
993
|
+
## Discriminated unions
|
|
990
994
|
|
|
991
995
|
If the union consists of object schemas all identifiable by a common property, it is possible to use
|
|
992
996
|
the `z.discriminatedUnion` method.
|
|
@@ -1032,7 +1036,7 @@ userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
|
|
|
1032
1036
|
}; // TypeError
|
|
1033
1037
|
```
|
|
1034
1038
|
|
|
1035
|
-
|
|
1039
|
+
**A note on numerical keys**
|
|
1036
1040
|
|
|
1037
1041
|
You may have expected `z.record()` to accept two arguments, one for the keys and one for the values. After all, TypeScript's built-in Record type does: `Record<KeyType, ValueType>` . Otherwise, how do you represent the TypeScript type `Record<number, any>` in Zod?
|
|
1038
1042
|
|
|
@@ -1049,9 +1053,7 @@ for (const key in testMap) {
|
|
|
1049
1053
|
// prints: `1: string`
|
|
1050
1054
|
```
|
|
1051
1055
|
|
|
1052
|
-
As you can see, JavaScript automatically casts all object keys to strings under the hood.
|
|
1053
|
-
|
|
1054
|
-
Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript.
|
|
1056
|
+
As you can see, JavaScript automatically casts all object keys to strings under the hood. Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript.
|
|
1055
1057
|
|
|
1056
1058
|
## Maps
|
|
1057
1059
|
|
|
@@ -1070,7 +1072,7 @@ type NumberSet = z.infer<typeof numberSet>;
|
|
|
1070
1072
|
// type NumberSet = Set<number>
|
|
1071
1073
|
```
|
|
1072
1074
|
|
|
1073
|
-
|
|
1075
|
+
Set schemas can be further contrainted with the following utility methods.
|
|
1074
1076
|
|
|
1075
1077
|
```ts
|
|
1076
1078
|
z.set(z.string()).nonempty(); // must contain at least one item
|
|
@@ -1081,8 +1083,6 @@ z.set(z.string()).size(5); // must contain 5 items exactly
|
|
|
1081
1083
|
|
|
1082
1084
|
## Intersections
|
|
1083
1085
|
|
|
1084
|
-
<!-- > ⚠️ Intersections are deprecated. If you are trying to merge objects, use the `.merge` method instead. -->
|
|
1085
|
-
|
|
1086
1086
|
Intersections are useful for creating "logical AND" types. This is useful for intersecting two object types.
|
|
1087
1087
|
|
|
1088
1088
|
```ts
|
|
@@ -1184,7 +1184,7 @@ const Category: z.ZodType<Category> = BaseCategory.merge(
|
|
|
1184
1184
|
);
|
|
1185
1185
|
``` -->
|
|
1186
1186
|
|
|
1187
|
-
|
|
1187
|
+
### JSON type
|
|
1188
1188
|
|
|
1189
1189
|
If you want to validate any JSON value, you can use the snippet below.
|
|
1190
1190
|
|
|
@@ -1201,7 +1201,7 @@ jsonSchema.parse(data);
|
|
|
1201
1201
|
|
|
1202
1202
|
Thanks to [ggoodman](https://github.com/ggoodman) for suggesting this.
|
|
1203
1203
|
|
|
1204
|
-
|
|
1204
|
+
### Cyclical objects
|
|
1205
1205
|
|
|
1206
1206
|
Despite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop.
|
|
1207
1207
|
|
|
@@ -1265,7 +1265,7 @@ type myFunction = z.infer<typeof myFunction>;
|
|
|
1265
1265
|
// => ()=>unknown
|
|
1266
1266
|
```
|
|
1267
1267
|
|
|
1268
|
-
|
|
1268
|
+
Define inputs and outputs.
|
|
1269
1269
|
|
|
1270
1270
|
```ts
|
|
1271
1271
|
const myFunction = z
|
|
@@ -1276,24 +1276,6 @@ type myFunction = z.infer<typeof myFunction>;
|
|
|
1276
1276
|
// => (arg0: string, arg1: number)=>boolean
|
|
1277
1277
|
```
|
|
1278
1278
|
|
|
1279
|
-
**Extract the input and output schemas**
|
|
1280
|
-
You can extract the parameters and return type of a function schema.
|
|
1281
|
-
|
|
1282
|
-
```ts
|
|
1283
|
-
myFunction.parameters();
|
|
1284
|
-
// => ZodTuple<[ZodString, ZodNumber]>
|
|
1285
|
-
|
|
1286
|
-
myFunction.returnType();
|
|
1287
|
-
// => ZodBoolean
|
|
1288
|
-
```
|
|
1289
|
-
|
|
1290
|
-
<!-- `z.function()` accepts two arguments:
|
|
1291
|
-
|
|
1292
|
-
* `args: ZodTuple` The first argument is a tuple (created with `z.tuple([...])` and defines the schema of the arguments to your function. If the function doesn't accept arguments, you can pass an empty tuple (`z.tuple([])`).
|
|
1293
|
-
* `returnType: any Zod schema` The second argument is the function's return type. This can be any Zod schema. -->
|
|
1294
|
-
|
|
1295
|
-
> You can use the special `z.void()` option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.)
|
|
1296
|
-
|
|
1297
1279
|
<!--
|
|
1298
1280
|
|
|
1299
1281
|
``` ts
|
|
@@ -1322,7 +1304,9 @@ trimmedLength("sandwich"); // => 8
|
|
|
1322
1304
|
trimmedLength(" asdf "); // => 4
|
|
1323
1305
|
```
|
|
1324
1306
|
|
|
1325
|
-
If you only care about validating inputs,
|
|
1307
|
+
If you only care about validating inputs, just don't call the `.returns()` method. The output type will be inferred from the implementation.
|
|
1308
|
+
|
|
1309
|
+
> You can use the special `z.void()` option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.)
|
|
1326
1310
|
|
|
1327
1311
|
```ts
|
|
1328
1312
|
const myFunction = z
|
|
@@ -1334,6 +1318,21 @@ const myFunction = z
|
|
|
1334
1318
|
myFunction; // (arg: string)=>number[]
|
|
1335
1319
|
```
|
|
1336
1320
|
|
|
1321
|
+
Extract the input and output schemas from a function schema.
|
|
1322
|
+
|
|
1323
|
+
```ts
|
|
1324
|
+
myFunction.parameters();
|
|
1325
|
+
// => ZodTuple<[ZodString, ZodNumber]>
|
|
1326
|
+
|
|
1327
|
+
myFunction.returnType();
|
|
1328
|
+
// => ZodBoolean
|
|
1329
|
+
```
|
|
1330
|
+
|
|
1331
|
+
<!-- `z.function()` accepts two arguments:
|
|
1332
|
+
|
|
1333
|
+
* `args: ZodTuple` The first argument is a tuple (created with `z.tuple([...])` and defines the schema of the arguments to your function. If the function doesn't accept arguments, you can pass an empty tuple (`z.tuple([])`).
|
|
1334
|
+
* `returnType: any Zod schema` The second argument is the function's return type. This can be any Zod schema. -->
|
|
1335
|
+
|
|
1337
1336
|
## Preprocess
|
|
1338
1337
|
|
|
1339
1338
|
Typically Zod operates under a "parse then transform" paradigm. Zod validates the input first, then passes it through a chain of transformation functions. (For more information about transforms, read the [.transform docs](#transform).)
|
|
@@ -1346,7 +1345,7 @@ const castToString = z.preprocess((val) => String(val), z.string());
|
|
|
1346
1345
|
|
|
1347
1346
|
This returns a `ZodEffects` instance. `ZodEffects` is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms.
|
|
1348
1347
|
|
|
1349
|
-
|
|
1348
|
+
## Schema methods
|
|
1350
1349
|
|
|
1351
1350
|
All Zod schemas contain certain methods.
|
|
1352
1351
|
|
|
@@ -1371,8 +1370,11 @@ stringSchema.parse(12); // throws Error('Non-string type: number');
|
|
|
1371
1370
|
If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync`
|
|
1372
1371
|
|
|
1373
1372
|
```ts
|
|
1374
|
-
const
|
|
1375
|
-
const
|
|
1373
|
+
const stringSchema1 = z.string().refine(async (val) => val.length < 20);
|
|
1374
|
+
const value1 = await stringSchema.parseAsync("hello"); // => hello
|
|
1375
|
+
|
|
1376
|
+
const stringSchema2 = z.string().refine(async (val) => val.length > 20);
|
|
1377
|
+
const value2 = await stringSchema.parseAsync("hello"); // => throws
|
|
1376
1378
|
```
|
|
1377
1379
|
|
|
1378
1380
|
### `.safeParse`
|
|
@@ -1607,27 +1609,6 @@ stringToNumber.parse("string"); // => 6
|
|
|
1607
1609
|
|
|
1608
1610
|
> ⚠️ Transform functions must not throw. Make sure to use refinements before the transform or addIssue within the transform to make sure the input can be parsed by the transform.
|
|
1609
1611
|
|
|
1610
|
-
#### Validating during transform
|
|
1611
|
-
|
|
1612
|
-
Similar to `superRefine`, `transform` can optionally take a `ctx`. This allows you to simultaneously
|
|
1613
|
-
validate and transform the value, which can be simpler than chaining `refine` and `validate`.
|
|
1614
|
-
When calling `ctx.addIssue` make sure to still return a value of the correct type otherwise the inferred type will include `undefined`.
|
|
1615
|
-
|
|
1616
|
-
```ts
|
|
1617
|
-
const Strings = z
|
|
1618
|
-
.string()
|
|
1619
|
-
.transform((val, ctx) => {
|
|
1620
|
-
const parsed = parseInt(val);
|
|
1621
|
-
if (isNaN(parsed)) {
|
|
1622
|
-
ctx.addIssue({
|
|
1623
|
-
code: z.ZodIssueCode.custom,
|
|
1624
|
-
message: "Not a number",
|
|
1625
|
-
});
|
|
1626
|
-
}
|
|
1627
|
-
return parsed;
|
|
1628
|
-
});
|
|
1629
|
-
```
|
|
1630
|
-
|
|
1631
1612
|
#### Chaining order
|
|
1632
1613
|
|
|
1633
1614
|
Note that `stringToNumber` above is an instance of the `ZodEffects` subclass. It is NOT an instance of `ZodString`. If you want to use the built-in methods of `ZodString` (e.g. `.email()`) you must apply those methods _before_ any transforms.
|
|
@@ -1641,14 +1622,33 @@ const emailToDomain = z
|
|
|
1641
1622
|
emailToDomain.parse("colinhacks@example.com"); // => example.com
|
|
1642
1623
|
```
|
|
1643
1624
|
|
|
1625
|
+
#### Validating during transform
|
|
1626
|
+
|
|
1627
|
+
Similar to `superRefine`, `transform` can optionally take a `ctx`. This allows you to simultaneously validate and transform the value, which can be simpler than chaining `refine` and `validate`. When calling `ctx.addIssue` make sure to still return a value of the correct type otherwise the inferred type will include `undefined`.
|
|
1628
|
+
|
|
1629
|
+
```ts
|
|
1630
|
+
const Strings = z.string().transform((val, ctx) => {
|
|
1631
|
+
const parsed = parseInt(val);
|
|
1632
|
+
if (isNaN(parsed)) {
|
|
1633
|
+
ctx.addIssue({
|
|
1634
|
+
code: z.ZodIssueCode.custom,
|
|
1635
|
+
message: "Not a number",
|
|
1636
|
+
});
|
|
1637
|
+
}
|
|
1638
|
+
return parsed;
|
|
1639
|
+
});
|
|
1640
|
+
```
|
|
1641
|
+
|
|
1644
1642
|
#### Relationship to refinements
|
|
1645
1643
|
|
|
1646
|
-
Transforms and refinements can be interleaved
|
|
1644
|
+
Transforms and refinements can be interleaved. These will be executed in the order they are declared.
|
|
1647
1645
|
|
|
1648
1646
|
```ts
|
|
1649
1647
|
z.string()
|
|
1650
|
-
.transform((val) => val.
|
|
1651
|
-
.refine((val) => val >
|
|
1648
|
+
.transform((val) => val.toUpperCase())
|
|
1649
|
+
.refine((val) => val.length > 15)
|
|
1650
|
+
.transform((val) => `Hello ${val}`)
|
|
1651
|
+
.refine((val) => val.indexOf("!") === -1);
|
|
1652
1652
|
```
|
|
1653
1653
|
|
|
1654
1654
|
#### Async transforms
|
|
@@ -1710,7 +1710,7 @@ z.nullable(z.string());
|
|
|
1710
1710
|
|
|
1711
1711
|
### `.nullish`
|
|
1712
1712
|
|
|
1713
|
-
A convenience method that returns a "nullish" version of a schema. Nullish schemas will accept both `undefined` and `null`. Read more about the concept of "nullish" [
|
|
1713
|
+
A convenience method that returns a "nullish" version of a schema. Nullish schemas will accept both `undefined` and `null`. Read more about the concept of "nullish" [in the TypeScript 3.7 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing).
|
|
1714
1714
|
|
|
1715
1715
|
```ts
|
|
1716
1716
|
const nullishString = z.string().nullish(); // string | null | undefined
|
|
@@ -1763,9 +1763,9 @@ z.object({ name: z.string() }).and(z.object({ age: z.number() })); // { name: st
|
|
|
1763
1763
|
z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() }));
|
|
1764
1764
|
```
|
|
1765
1765
|
|
|
1766
|
-
|
|
1766
|
+
## Guides and concepts
|
|
1767
1767
|
|
|
1768
|
-
|
|
1768
|
+
### Type inference
|
|
1769
1769
|
|
|
1770
1770
|
You can extract the TypeScript type of any schema with `z.infer<typeof mySchema>` .
|
|
1771
1771
|
|
|
@@ -1777,7 +1777,7 @@ const u: A = 12; // TypeError
|
|
|
1777
1777
|
const u: A = "asdf"; // compiles
|
|
1778
1778
|
```
|
|
1779
1779
|
|
|
1780
|
-
|
|
1780
|
+
**What about transforms?**
|
|
1781
1781
|
|
|
1782
1782
|
In reality each Zod schema internally tracks **two** types: an input and an output. For most schemas (e.g. `z.string()`) these two are the same. But once you add transforms into the mix, these two values can diverge. For instance `z.string().transform(val => val.length)` has an input of `string` and an output of `number`.
|
|
1783
1783
|
|
|
@@ -1794,7 +1794,7 @@ type output = z.output<typeof stringToNumber>; // number
|
|
|
1794
1794
|
type inferred = z.infer<typeof stringToNumber>; // number
|
|
1795
1795
|
```
|
|
1796
1796
|
|
|
1797
|
-
|
|
1797
|
+
### Writing generic functions
|
|
1798
1798
|
|
|
1799
1799
|
When attempting to write a functions that accepts a Zod schemas as an input, it's common to try something like this:
|
|
1800
1800
|
|
|
@@ -1828,13 +1828,13 @@ const arg = makeSchemaOptional(z.string());
|
|
|
1828
1828
|
arg.unwrap(); // ZodString
|
|
1829
1829
|
```
|
|
1830
1830
|
|
|
1831
|
-
|
|
1831
|
+
#### Constraining allowable inputs
|
|
1832
1832
|
|
|
1833
1833
|
The `ZodType` class has three generic parameters.
|
|
1834
1834
|
|
|
1835
1835
|
```ts
|
|
1836
1836
|
class ZodType<
|
|
1837
|
-
Output,
|
|
1837
|
+
Output = any,
|
|
1838
1838
|
Def extends ZodTypeDef = ZodTypeDef,
|
|
1839
1839
|
Input = Output
|
|
1840
1840
|
> { ... }
|
|
@@ -1854,12 +1854,16 @@ makeSchemaOptional(z.number());
|
|
|
1854
1854
|
// Error: 'ZodNumber' is not assignable to parameter of type 'ZodType<string, ZodTypeDef, string>'
|
|
1855
1855
|
```
|
|
1856
1856
|
|
|
1857
|
-
|
|
1857
|
+
### Error handling
|
|
1858
1858
|
|
|
1859
1859
|
Zod provides a subclass of Error called `ZodError`. ZodErrors contain an `issues` array containing detailed information about the validation problems.
|
|
1860
1860
|
|
|
1861
1861
|
```ts
|
|
1862
|
-
const data = z
|
|
1862
|
+
const data = z
|
|
1863
|
+
.object({
|
|
1864
|
+
name: z.string(),
|
|
1865
|
+
})
|
|
1866
|
+
.safeParse({ name: 12 });
|
|
1863
1867
|
|
|
1864
1868
|
if (!data.success) {
|
|
1865
1869
|
data.error.issues;
|
|
@@ -1875,20 +1879,31 @@ if (!data.success) {
|
|
|
1875
1879
|
}
|
|
1876
1880
|
```
|
|
1877
1881
|
|
|
1878
|
-
|
|
1882
|
+
> For detailed information about the possible error codes and how to customize error messages, check out the dedicated error handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md)
|
|
1883
|
+
|
|
1884
|
+
### Error formatting
|
|
1879
1885
|
|
|
1880
1886
|
You can use the `.format()` method to convert this error into a nested object.
|
|
1881
1887
|
|
|
1882
1888
|
```ts
|
|
1883
|
-
data
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
}
|
|
1887
|
-
|
|
1889
|
+
const data = z
|
|
1890
|
+
.object({
|
|
1891
|
+
name: z.string(),
|
|
1892
|
+
})
|
|
1893
|
+
.safeParse({ name: 12 });
|
|
1888
1894
|
|
|
1889
|
-
|
|
1895
|
+
if (!data.success) {
|
|
1896
|
+
const formatted = data.error.format();
|
|
1897
|
+
/* {
|
|
1898
|
+
name: { _errors: [ 'Expected string, received number' ] }
|
|
1899
|
+
} */
|
|
1890
1900
|
|
|
1891
|
-
|
|
1901
|
+
formatted.name?._errors;
|
|
1902
|
+
// => ["Expected string, received number"]
|
|
1903
|
+
}
|
|
1904
|
+
```
|
|
1905
|
+
|
|
1906
|
+
## Comparison
|
|
1892
1907
|
|
|
1893
1908
|
There are a handful of other widely-used validation libraries, but all of them have certain design limitations that make for a non-ideal developer experience.
|
|
1894
1909
|
|
|
@@ -1940,20 +1955,18 @@ Branded -->
|
|
|
1940
1955
|
* Missing support for parsing cyclical data (maybe)
|
|
1941
1956
|
* Missing error customization -->
|
|
1942
1957
|
|
|
1943
|
-
|
|
1958
|
+
**Joi**
|
|
1944
1959
|
|
|
1945
1960
|
[https://github.com/hapijs/joi](https://github.com/hapijs/joi)
|
|
1946
1961
|
|
|
1947
1962
|
Doesn't support static type inference 😕
|
|
1948
1963
|
|
|
1949
|
-
|
|
1964
|
+
**Yup**
|
|
1950
1965
|
|
|
1951
1966
|
[https://github.com/jquense/yup](https://github.com/jquense/yup)
|
|
1952
1967
|
|
|
1953
1968
|
Yup is a full-featured library that was implemented first in vanilla JS, and later rewritten in TypeScript.
|
|
1954
1969
|
|
|
1955
|
-
Differences
|
|
1956
|
-
|
|
1957
1970
|
- Supports casting and transforms
|
|
1958
1971
|
- All object fields are optional by default
|
|
1959
1972
|
- Missing object methods: (partial, deepPartial)
|
|
@@ -1964,7 +1977,7 @@ Differences
|
|
|
1964
1977
|
|
|
1965
1978
|
<!-- ¹Yup has a strange interpretation of the word `required`. Instead of meaning "not undefined", Yup uses it to mean "not empty". So `yup.string().required()` will not accept an empty string, and `yup.array(yup.string()).required()` will not accept an empty array. Instead, Yup us Zod arrays there is a dedicated `.nonempty()` method to indicate this, or you can implement it with a custom refinement. -->
|
|
1966
1979
|
|
|
1967
|
-
|
|
1980
|
+
**io-ts**
|
|
1968
1981
|
|
|
1969
1982
|
[https://github.com/gcanti/io-ts](https://github.com/gcanti/io-ts)
|
|
1970
1983
|
|
|
@@ -2015,7 +2028,7 @@ This more declarative API makes schema definitions vastly more concise.
|
|
|
2015
2028
|
- Missing promise schemas
|
|
2016
2029
|
- Missing function schemas
|
|
2017
2030
|
|
|
2018
|
-
|
|
2031
|
+
**Runtypes**
|
|
2019
2032
|
|
|
2020
2033
|
[https://github.com/pelotom/runtypes](https://github.com/pelotom/runtypes)
|
|
2021
2034
|
|
|
@@ -2028,7 +2041,7 @@ Good type inference support, but limited options for object type masking (no `.p
|
|
|
2028
2041
|
- Missing promise schemas
|
|
2029
2042
|
- Missing error customization
|
|
2030
2043
|
|
|
2031
|
-
|
|
2044
|
+
**Ow**
|
|
2032
2045
|
|
|
2033
2046
|
[https://github.com/sindresorhus/ow](https://github.com/sindresorhus/ow)
|
|
2034
2047
|
|
|
@@ -2036,6 +2049,6 @@ Ow is focused on function input validation. It's a library that makes it easy to
|
|
|
2036
2049
|
|
|
2037
2050
|
If you want to validate function inputs, use function schemas in Zod! It's a much simpler approach that lets you reuse a function type declaration without repeating yourself (namely, copy-pasting a bunch of ow assertions at the beginning of every function). Also Zod lets you validate your return types as well, so you can be sure there won't be any unexpected data passed downstream.
|
|
2038
2051
|
|
|
2039
|
-
|
|
2052
|
+
## Changelog
|
|
2040
2053
|
|
|
2041
2054
|
View the changelog at [CHANGELOG.md](CHANGELOG.md)
|
package/lib/index.mjs
CHANGED
|
@@ -709,8 +709,8 @@ class ZodString extends ZodType {
|
|
|
709
709
|
...errorUtil.errToObj(message),
|
|
710
710
|
});
|
|
711
711
|
/**
|
|
712
|
-
*
|
|
713
|
-
*
|
|
712
|
+
* @deprecated Use z.string().min(1) instead.
|
|
713
|
+
* @see {@link ZodString.min}
|
|
714
714
|
*/
|
|
715
715
|
this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
|
|
716
716
|
}
|
|
@@ -2721,9 +2721,15 @@ ZodNaN.create = (params) => {
|
|
|
2721
2721
|
...processCreateParams(params),
|
|
2722
2722
|
});
|
|
2723
2723
|
};
|
|
2724
|
-
const custom = (check, params) => {
|
|
2724
|
+
const custom = (check, params = {}, fatal) => {
|
|
2725
2725
|
if (check)
|
|
2726
|
-
return ZodAny.create().
|
|
2726
|
+
return ZodAny.create().superRefine((data, ctx) => {
|
|
2727
|
+
if (!check(data)) {
|
|
2728
|
+
const p = typeof params === "function" ? params(data) : params;
|
|
2729
|
+
const p2 = typeof p === "string" ? { message: p } : p;
|
|
2730
|
+
ctx.addIssue({ code: "custom", ...p2, fatal });
|
|
2731
|
+
}
|
|
2732
|
+
});
|
|
2727
2733
|
return ZodAny.create();
|
|
2728
2734
|
};
|
|
2729
2735
|
const late = {
|
|
@@ -2765,7 +2771,7 @@ var ZodFirstPartyTypeKind;
|
|
|
2765
2771
|
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
|
|
2766
2772
|
const instanceOfType = (cls, params = {
|
|
2767
2773
|
message: `Input not instance of ${cls.name}`,
|
|
2768
|
-
}) => custom((data) => data instanceof cls, params);
|
|
2774
|
+
}) => custom((data) => data instanceof cls, params, true);
|
|
2769
2775
|
const stringType = ZodString.create;
|
|
2770
2776
|
const numberType = ZodNumber.create;
|
|
2771
2777
|
const nanType = ZodNaN.create;
|
package/lib/index.umd.js
CHANGED
|
@@ -715,8 +715,8 @@
|
|
|
715
715
|
...errorUtil.errToObj(message),
|
|
716
716
|
});
|
|
717
717
|
/**
|
|
718
|
-
*
|
|
719
|
-
*
|
|
718
|
+
* @deprecated Use z.string().min(1) instead.
|
|
719
|
+
* @see {@link ZodString.min}
|
|
720
720
|
*/
|
|
721
721
|
this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
|
|
722
722
|
}
|
|
@@ -2727,9 +2727,15 @@
|
|
|
2727
2727
|
...processCreateParams(params),
|
|
2728
2728
|
});
|
|
2729
2729
|
};
|
|
2730
|
-
const custom = (check, params) => {
|
|
2730
|
+
const custom = (check, params = {}, fatal) => {
|
|
2731
2731
|
if (check)
|
|
2732
|
-
return ZodAny.create().
|
|
2732
|
+
return ZodAny.create().superRefine((data, ctx) => {
|
|
2733
|
+
if (!check(data)) {
|
|
2734
|
+
const p = typeof params === "function" ? params(data) : params;
|
|
2735
|
+
const p2 = typeof p === "string" ? { message: p } : p;
|
|
2736
|
+
ctx.addIssue({ code: "custom", ...p2, fatal });
|
|
2737
|
+
}
|
|
2738
|
+
});
|
|
2733
2739
|
return ZodAny.create();
|
|
2734
2740
|
};
|
|
2735
2741
|
const late = {
|
|
@@ -2771,7 +2777,7 @@
|
|
|
2771
2777
|
})(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
|
|
2772
2778
|
const instanceOfType = (cls, params = {
|
|
2773
2779
|
message: `Input not instance of ${cls.name}`,
|
|
2774
|
-
}) => custom((data) => data instanceof cls, params);
|
|
2780
|
+
}) => custom((data) => data instanceof cls, params, true);
|
|
2775
2781
|
const stringType = ZodString.create;
|
|
2776
2782
|
const numberType = ZodNumber.create;
|
|
2777
2783
|
const nanType = ZodNaN.create;
|
package/lib/types.d.ts
CHANGED
|
@@ -120,8 +120,8 @@ export declare class ZodString extends ZodType<string, ZodStringDef> {
|
|
|
120
120
|
max(maxLength: number, message?: errorUtil.ErrMessage): ZodString;
|
|
121
121
|
length(len: number, message?: errorUtil.ErrMessage): ZodString;
|
|
122
122
|
/**
|
|
123
|
-
*
|
|
124
|
-
*
|
|
123
|
+
* @deprecated Use z.string().min(1) instead.
|
|
124
|
+
* @see {@link ZodString.min}
|
|
125
125
|
*/
|
|
126
126
|
nonempty: (message?: errorUtil.ErrMessage | undefined) => ZodString;
|
|
127
127
|
get isEmail(): boolean;
|
|
@@ -625,7 +625,7 @@ export declare class ZodNaN extends ZodType<number, ZodNaNDef> {
|
|
|
625
625
|
_parse(input: ParseInput): ParseReturnType<any>;
|
|
626
626
|
static create: (params?: RawCreateParams) => ZodNaN;
|
|
627
627
|
}
|
|
628
|
-
export declare const custom: <T>(check?: ((data: unknown) => any) | undefined, params?: Parameters<ZodTypeAny["refine"]>[1]) => ZodType<T, ZodTypeDef, T>;
|
|
628
|
+
export declare const custom: <T>(check?: ((data: unknown) => any) | undefined, params?: Parameters<ZodTypeAny["refine"]>[1], fatal?: boolean | undefined) => ZodType<T, ZodTypeDef, T>;
|
|
629
629
|
export { ZodType as Schema, ZodType as ZodSchema };
|
|
630
630
|
export declare const late: {
|
|
631
631
|
object: <T extends ZodRawShape>(shape: () => T, params?: RawCreateParams) => ZodObject<T, "strip", ZodTypeAny, { [k_1 in keyof objectUtil.addQuestionMarks<{ [k in keyof T]: T[k]["_output"]; }>]: objectUtil.addQuestionMarks<{ [k in keyof T]: T[k]["_output"]; }>[k_1]; }, { [k_3 in keyof objectUtil.addQuestionMarks<{ [k_2 in keyof T]: T[k_2]["_input"]; }>]: objectUtil.addQuestionMarks<{ [k_2 in keyof T]: T[k_2]["_input"]; }>[k_3]; }>;
|
package/lib/types.js
CHANGED
|
@@ -291,8 +291,8 @@ class ZodString extends ZodType {
|
|
|
291
291
|
...errorUtil_1.errorUtil.errToObj(message),
|
|
292
292
|
});
|
|
293
293
|
/**
|
|
294
|
-
*
|
|
295
|
-
*
|
|
294
|
+
* @deprecated Use z.string().min(1) instead.
|
|
295
|
+
* @see {@link ZodString.min}
|
|
296
296
|
*/
|
|
297
297
|
this.nonempty = (message) => this.min(1, errorUtil_1.errorUtil.errToObj(message));
|
|
298
298
|
}
|
|
@@ -2336,9 +2336,15 @@ ZodNaN.create = (params) => {
|
|
|
2336
2336
|
...processCreateParams(params),
|
|
2337
2337
|
});
|
|
2338
2338
|
};
|
|
2339
|
-
const custom = (check, params) => {
|
|
2339
|
+
const custom = (check, params = {}, fatal) => {
|
|
2340
2340
|
if (check)
|
|
2341
|
-
return ZodAny.create().
|
|
2341
|
+
return ZodAny.create().superRefine((data, ctx) => {
|
|
2342
|
+
if (!check(data)) {
|
|
2343
|
+
const p = typeof params === "function" ? params(data) : params;
|
|
2344
|
+
const p2 = typeof p === "string" ? { message: p } : p;
|
|
2345
|
+
ctx.addIssue({ code: "custom", ...p2, fatal });
|
|
2346
|
+
}
|
|
2347
|
+
});
|
|
2342
2348
|
return ZodAny.create();
|
|
2343
2349
|
};
|
|
2344
2350
|
exports.custom = custom;
|
|
@@ -2381,7 +2387,7 @@ var ZodFirstPartyTypeKind;
|
|
|
2381
2387
|
})(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
|
|
2382
2388
|
const instanceOfType = (cls, params = {
|
|
2383
2389
|
message: `Input not instance of ${cls.name}`,
|
|
2384
|
-
}) => (0, exports.custom)((data) => data instanceof cls, params);
|
|
2390
|
+
}) => (0, exports.custom)((data) => data instanceof cls, params, true);
|
|
2385
2391
|
exports.instanceof = instanceOfType;
|
|
2386
2392
|
const stringType = ZodString.create;
|
|
2387
2393
|
exports.string = stringType;
|