From 1e74925c362df54be821011043c15f354c2c24e2 Mon Sep 17 00:00:00 2001 From: Landon Yarrington <33426811+jly36963@users.noreply.github.com> Date: Wed, 8 Feb 2023 00:31:33 -0700 Subject: [PATCH] docs: punctuation (#1973) * docs: punctuation * Tweaks --------- Co-authored-by: Colin McDonnell --- README.md | 120 +++++++++++++++++++++++---------------------- deno/lib/README.md | 120 +++++++++++++++++++++++---------------------- 2 files changed, 124 insertions(+), 116 deletions(-) diff --git a/README.md b/README.md index 34b33fc22..ad959fb9c 100644 --- a/README.md +++ b/README.md @@ -745,19 +745,19 @@ z.date().max(new Date(), { message: "Too young!" }); Since [zod 3.20](https://github.com/colinhacks/zod/releases/tag/v3.20), use [`z.coerce.date()`](#coercion-for-primitives) to pass the input through `new Date(input)`. ```ts -const dateSchema = z.coerce.date() -type DateSchema = z.infer +const dateSchema = z.coerce.date(); +type DateSchema = z.infer; // type DateSchema = Date /* valid dates */ -console.log( dateSchema.safeParse( '2023-01-10T00:00:00.000Z' ).success ) // true -console.log( dateSchema.safeParse( '2023-01-10' ).success ) // true -console.log( dateSchema.safeParse( '1/10/23' ).success ) // true -console.log( dateSchema.safeParse( new Date( '1/10/23' ) ).success ) // true +console.log(dateSchema.safeParse("2023-01-10T00:00:00.000Z").success); // true +console.log(dateSchema.safeParse("2023-01-10").success); // true +console.log(dateSchema.safeParse("1/10/23").success); // true +console.log(dateSchema.safeParse(new Date("1/10/23")).success); // true /* invalid dates */ -console.log( dateSchema.safeParse( '2023-13-10' ).success ) // false -console.log( dateSchema.safeParse( '0000-00-00' ).success ) // false +console.log(dateSchema.safeParse("2023-13-10").success); // false +console.log(dateSchema.safeParse("0000-00-00").success); // false ``` For older zod versions, use [`z.preprocess`](#preprocess) like [described in this thread](https://github.com/colinhacks/zod/discussions/879#discussioncomment-2036276). @@ -1301,16 +1301,13 @@ To validate an optional form input, you can union the desired string validation This example validates an input that is optional but needs to contain a [valid URL](#strings): ```ts -const optionalUrl = z.union( [ - z.string().url().nullish(), - z.literal( '' ), -] ) +const optionalUrl = z.union([z.string().url().nullish(), z.literal("")]); -console.log( optionalUrl.safeParse( undefined ).success ) // true -console.log( optionalUrl.safeParse( null ).success ) // true -console.log( optionalUrl.safeParse( '' ).success ) // true -console.log( optionalUrl.safeParse( 'https://zod.dev' ).success ) // true -console.log( optionalUrl.safeParse( 'not a valid url' ).success ) // false +console.log(optionalUrl.safeParse(undefined).success); // true +console.log(optionalUrl.safeParse(null).success); // true +console.log(optionalUrl.safeParse("").success); // true +console.log(optionalUrl.safeParse("https://zod.dev").success); // true +console.log(optionalUrl.safeParse("not a valid url").success); // false ``` ## Discriminated unions @@ -1325,7 +1322,7 @@ type MyUnion = Such unions can be represented with the `z.discriminatedUnion` method. This enables faster evaluation, because Zod can check the _discriminator key_ (`status` in the example above) to determine which schema should be used to parse the input. This makes parsing more efficient and lets Zod report friendlier errors. -With the basic union method the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option". +With the basic union method, the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option". ```ts const myUnion = z.discriminatedUnion("status", [ @@ -1474,59 +1471,64 @@ type Teacher = z.infer; You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint". ```ts -const baseCategorySchema = z.object( { - name: z.string(), -} ) +const baseCategorySchema = z.object({ + name: z.string(), +}); type Category = z.infer & { - subcategories: Category[] -} + subcategories: Category[]; +}; -const categorySchema: z.ZodType = baseCategorySchema.extend( { - subcategories: z.lazy( () => categorySchema.array() ), -} ) +const categorySchema: z.ZodType = baseCategorySchema.extend({ + subcategories: z.lazy(() => categorySchema.array()), +}); -categorySchema.parse( { - name: 'People', - subcategories: [ { - name: 'Politicians', - subcategories: [ { - name: 'Presidents', - subcategories: [] - } ], - } ], -} ) // passes +categorySchema.parse({ + name: "People", + subcategories: [ + { + name: "Politicians", + subcategories: [ + { + name: "Presidents", + subcategories: [], + }, + ], + }, + ], +}); // passes ``` Thanks to [crasite](https://github.com/crasite) for this example. ### ZodType with ZodEffects + When using `z.ZodType` with `z.ZodEffects` ( - [`.refine`](https://github.com/colinhacks/zod#refine), - [`.transform`](https://github.com/colinhacks/zod#transform), - [`preprocess`](https://github.com/colinhacks/zod#preprocess), - etc... +[`.refine`](https://github.com/colinhacks/zod#refine), +[`.transform`](https://github.com/colinhacks/zod#transform), +[`preprocess`](https://github.com/colinhacks/zod#preprocess), +etc... ), you will need to define the input and output types of the schema. `z.ZodType` ```ts -const isValidId = ( id: string ): id is `${ string }/${ string }` => - id.split( '/' ).length === 2 +const isValidId = (id: string): id is `${string}/${string}` => + id.split("/").length === 2; -const baseSchema = z.object( { - id: z.string().refine( isValidId ) -} ) +const baseSchema = z.object({ + id: z.string().refine(isValidId), +}); type Input = z.input & { - children: Input[] -} + children: Input[]; +}; type Output = z.output & { - children: Output[] -} + children: Output[]; +}; -const schema: z.ZodType = baseSchema.extend( { - children: z.lazy( () => schema.array() ), -} ) +const schema: z.ZodType = baseSchema.extend({ + children: z.lazy(() => schema.array()), +}); ``` Thanks to [marcus13371337](https://github.com/marcus13371337) and [JoelBeeldi](https://github.com/JoelBeeldi) for this example. @@ -1735,7 +1737,7 @@ stringSchema.parse(12); // throws error `.parseAsync(data:unknown): Promise` -If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync` +If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync`. ```ts const stringSchema = z.string().refine(async (val) => val.length <= 8); @@ -1758,7 +1760,7 @@ stringSchema.safeParse("billie"); // => { success: true; data: 'billie' } ``` -The result is a _discriminated union_ so you can handle errors very conveniently: +The result is a _discriminated union_, so you can handle errors very conveniently: ```ts const result = stringSchema.safeParse("billie"); @@ -2018,7 +2020,7 @@ emailToDomain.parse("colinhacks@example.com"); // => example.com The `.transform` method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining `transform` and `refine`. -As with `.superRefine`, the transform function receives a `ctx` object with a `addIssue` method that can be used to register validation issues. +As with `.superRefine`, the transform function receives a `ctx` object with an `addIssue` method that can be used to register validation issues. ```ts const numberInString = z.string().transform((val, ctx) => { @@ -2097,8 +2099,10 @@ Conceptually, this is how Zod processes default values: Use `.describe()` to add a `description` property to the resulting schema. ```ts -const documentedString = z.string().describe("A useful bit of text, if you know what to do with it."); -documentedString.description // A useful bit of text… +const documentedString = z + .string() + .describe("A useful bit of text, if you know what to do with it."); +documentedString.description; // A useful bit of text… ``` This can be useful for documenting a field, for example in a JSON Schema using a library like [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema)). @@ -2367,7 +2371,7 @@ if (!data.success) { > 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) -Zod's error reporting emphasizes _completeness_ and _correctness_. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third party library like [`zod-validation-error`](https://github.com/causaly/zod-validation-error) +Zod's error reporting emphasizes _completeness_ and _correctness_. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third-party library like [`zod-validation-error`](https://github.com/causaly/zod-validation-error) ### Error formatting diff --git a/deno/lib/README.md b/deno/lib/README.md index 34b33fc22..ad959fb9c 100644 --- a/deno/lib/README.md +++ b/deno/lib/README.md @@ -745,19 +745,19 @@ z.date().max(new Date(), { message: "Too young!" }); Since [zod 3.20](https://github.com/colinhacks/zod/releases/tag/v3.20), use [`z.coerce.date()`](#coercion-for-primitives) to pass the input through `new Date(input)`. ```ts -const dateSchema = z.coerce.date() -type DateSchema = z.infer +const dateSchema = z.coerce.date(); +type DateSchema = z.infer; // type DateSchema = Date /* valid dates */ -console.log( dateSchema.safeParse( '2023-01-10T00:00:00.000Z' ).success ) // true -console.log( dateSchema.safeParse( '2023-01-10' ).success ) // true -console.log( dateSchema.safeParse( '1/10/23' ).success ) // true -console.log( dateSchema.safeParse( new Date( '1/10/23' ) ).success ) // true +console.log(dateSchema.safeParse("2023-01-10T00:00:00.000Z").success); // true +console.log(dateSchema.safeParse("2023-01-10").success); // true +console.log(dateSchema.safeParse("1/10/23").success); // true +console.log(dateSchema.safeParse(new Date("1/10/23")).success); // true /* invalid dates */ -console.log( dateSchema.safeParse( '2023-13-10' ).success ) // false -console.log( dateSchema.safeParse( '0000-00-00' ).success ) // false +console.log(dateSchema.safeParse("2023-13-10").success); // false +console.log(dateSchema.safeParse("0000-00-00").success); // false ``` For older zod versions, use [`z.preprocess`](#preprocess) like [described in this thread](https://github.com/colinhacks/zod/discussions/879#discussioncomment-2036276). @@ -1301,16 +1301,13 @@ To validate an optional form input, you can union the desired string validation This example validates an input that is optional but needs to contain a [valid URL](#strings): ```ts -const optionalUrl = z.union( [ - z.string().url().nullish(), - z.literal( '' ), -] ) +const optionalUrl = z.union([z.string().url().nullish(), z.literal("")]); -console.log( optionalUrl.safeParse( undefined ).success ) // true -console.log( optionalUrl.safeParse( null ).success ) // true -console.log( optionalUrl.safeParse( '' ).success ) // true -console.log( optionalUrl.safeParse( 'https://zod.dev' ).success ) // true -console.log( optionalUrl.safeParse( 'not a valid url' ).success ) // false +console.log(optionalUrl.safeParse(undefined).success); // true +console.log(optionalUrl.safeParse(null).success); // true +console.log(optionalUrl.safeParse("").success); // true +console.log(optionalUrl.safeParse("https://zod.dev").success); // true +console.log(optionalUrl.safeParse("not a valid url").success); // false ``` ## Discriminated unions @@ -1325,7 +1322,7 @@ type MyUnion = Such unions can be represented with the `z.discriminatedUnion` method. This enables faster evaluation, because Zod can check the _discriminator key_ (`status` in the example above) to determine which schema should be used to parse the input. This makes parsing more efficient and lets Zod report friendlier errors. -With the basic union method the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option". +With the basic union method, the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option". ```ts const myUnion = z.discriminatedUnion("status", [ @@ -1474,59 +1471,64 @@ type Teacher = z.infer; You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint". ```ts -const baseCategorySchema = z.object( { - name: z.string(), -} ) +const baseCategorySchema = z.object({ + name: z.string(), +}); type Category = z.infer & { - subcategories: Category[] -} + subcategories: Category[]; +}; -const categorySchema: z.ZodType = baseCategorySchema.extend( { - subcategories: z.lazy( () => categorySchema.array() ), -} ) +const categorySchema: z.ZodType = baseCategorySchema.extend({ + subcategories: z.lazy(() => categorySchema.array()), +}); -categorySchema.parse( { - name: 'People', - subcategories: [ { - name: 'Politicians', - subcategories: [ { - name: 'Presidents', - subcategories: [] - } ], - } ], -} ) // passes +categorySchema.parse({ + name: "People", + subcategories: [ + { + name: "Politicians", + subcategories: [ + { + name: "Presidents", + subcategories: [], + }, + ], + }, + ], +}); // passes ``` Thanks to [crasite](https://github.com/crasite) for this example. ### ZodType with ZodEffects + When using `z.ZodType` with `z.ZodEffects` ( - [`.refine`](https://github.com/colinhacks/zod#refine), - [`.transform`](https://github.com/colinhacks/zod#transform), - [`preprocess`](https://github.com/colinhacks/zod#preprocess), - etc... +[`.refine`](https://github.com/colinhacks/zod#refine), +[`.transform`](https://github.com/colinhacks/zod#transform), +[`preprocess`](https://github.com/colinhacks/zod#preprocess), +etc... ), you will need to define the input and output types of the schema. `z.ZodType` ```ts -const isValidId = ( id: string ): id is `${ string }/${ string }` => - id.split( '/' ).length === 2 +const isValidId = (id: string): id is `${string}/${string}` => + id.split("/").length === 2; -const baseSchema = z.object( { - id: z.string().refine( isValidId ) -} ) +const baseSchema = z.object({ + id: z.string().refine(isValidId), +}); type Input = z.input & { - children: Input[] -} + children: Input[]; +}; type Output = z.output & { - children: Output[] -} + children: Output[]; +}; -const schema: z.ZodType = baseSchema.extend( { - children: z.lazy( () => schema.array() ), -} ) +const schema: z.ZodType = baseSchema.extend({ + children: z.lazy(() => schema.array()), +}); ``` Thanks to [marcus13371337](https://github.com/marcus13371337) and [JoelBeeldi](https://github.com/JoelBeeldi) for this example. @@ -1735,7 +1737,7 @@ stringSchema.parse(12); // throws error `.parseAsync(data:unknown): Promise` -If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync` +If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync`. ```ts const stringSchema = z.string().refine(async (val) => val.length <= 8); @@ -1758,7 +1760,7 @@ stringSchema.safeParse("billie"); // => { success: true; data: 'billie' } ``` -The result is a _discriminated union_ so you can handle errors very conveniently: +The result is a _discriminated union_, so you can handle errors very conveniently: ```ts const result = stringSchema.safeParse("billie"); @@ -2018,7 +2020,7 @@ emailToDomain.parse("colinhacks@example.com"); // => example.com The `.transform` method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining `transform` and `refine`. -As with `.superRefine`, the transform function receives a `ctx` object with a `addIssue` method that can be used to register validation issues. +As with `.superRefine`, the transform function receives a `ctx` object with an `addIssue` method that can be used to register validation issues. ```ts const numberInString = z.string().transform((val, ctx) => { @@ -2097,8 +2099,10 @@ Conceptually, this is how Zod processes default values: Use `.describe()` to add a `description` property to the resulting schema. ```ts -const documentedString = z.string().describe("A useful bit of text, if you know what to do with it."); -documentedString.description // A useful bit of text… +const documentedString = z + .string() + .describe("A useful bit of text, if you know what to do with it."); +documentedString.description; // A useful bit of text… ``` This can be useful for documenting a field, for example in a JSON Schema using a library like [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema)). @@ -2367,7 +2371,7 @@ if (!data.success) { > 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) -Zod's error reporting emphasizes _completeness_ and _correctness_. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third party library like [`zod-validation-error`](https://github.com/causaly/zod-validation-error) +Zod's error reporting emphasizes _completeness_ and _correctness_. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third-party library like [`zod-validation-error`](https://github.com/causaly/zod-validation-error) ### Error formatting