mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Incorporate Existing Type Into Zod Schema as a Zod TIL
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
46
zod/incorporate-existing-type-into-zod-schema.md
Normal file
46
zod/incorporate-existing-type-into-zod-schema.md
Normal file
@@ -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<Book> = 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)
|
||||
Reference in New Issue
Block a user