From e80721bb6fc89609c1052bbe197cea44375070e4 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 22 Dec 2022 14:02:32 -0600 Subject: [PATCH] Add Incorporate Existing Type Into Zod Schema as a Zod TIL --- README.md | 3 +- ...corporate-existing-type-into-zod-schema.md | 46 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 zod/incorporate-existing-type-into-zod-schema.md diff --git a/README.md b/README.md index 3c9e8fb..e3e1053 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1271 TILs and counting..._ +_1272 TILs and counting..._ --- @@ -1511,6 +1511,7 @@ _1271 TILs and counting..._ - [Check If An Object Is Empty With Zod](zod/check-if-an-object-is-empty-with-zod.md) - [Create Union Type Of Nearly Identical Objects](zod/create-union-type-of-nearly-identical-objects.md) +- [Incorporate Existing Type Into Zod Schema](zod/incorporate-existing-type-into-zod-schema.md) ## Usage diff --git a/zod/incorporate-existing-type-into-zod-schema.md b/zod/incorporate-existing-type-into-zod-schema.md new file mode 100644 index 0000000..46d870c --- /dev/null +++ b/zod/incorporate-existing-type-into-zod-schema.md @@ -0,0 +1,46 @@ +# Incorporate Existing Type Into Zod Schema + +Zod's API is great for quickly scaffolding the shape of data that we're +working with. This breaks down when data has a more complex shape and is coming +from somewhere else, like a Prisma client. The shape of the data, and types +provided by the library, are determined somewhere else. We want to leverage +that rather than redefine it. + +Fortunately, Zod has a way for us to incorporate an existing type into a Zod +schema that we're building. + +```typescript +import {z} from 'zod' +import {Book} from '@prisma/client' + +const BookOrder = z.object({ + customer: z.object({ + email: z.string().email(), + name: z.string() + }), + books: // how do we use the `Book` type here? +}) +``` + +We can turn the `Book` type into a Zod type that we can use in our schema with +`z.ZodType` and `z.any`. + +```typescript +import {z} from 'zod' +import {Book} from '@prisma/client' + +const BookSchema: z.ZodType = z.any() + +const BookOrder = z.object({ + customer: z.object({ + email: z.string().email(), + name: z.string() + }), + books: BookSchema.array() +}) +``` + +We create a `BookSchema` with `z.any` and then narrow it to a `z.ZodType` with +our `Book` type. + +[source](https://github.com/colinhacks/zod/issues/52#issuecomment-629897855)