mirror of
https://github.com/jbranchaud/til
synced 2026-01-19 15:08:02 +00:00
Add Create A Schema That Matches On Any Object 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).
|
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||||
|
|
||||||
_1276 TILs and counting..._
|
_1277 TILs and counting..._
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -1514,6 +1514,7 @@ _1276 TILs and counting..._
|
|||||||
### Zod
|
### Zod
|
||||||
|
|
||||||
- [Check If An Object Is Empty With Zod](zod/check-if-an-object-is-empty-with-zod.md)
|
- [Check If An Object Is Empty With Zod](zod/check-if-an-object-is-empty-with-zod.md)
|
||||||
|
- [Create A Schema That Matches On Any Object](zod/create-a-schema-that-matches-on-any-object.md)
|
||||||
- [Create Union Type Of Nearly Identical Objects](zod/create-union-type-of-nearly-identical-objects.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)
|
- [Incorporate Existing Type Into Zod Schema](zod/incorporate-existing-type-into-zod-schema.md)
|
||||||
|
|
||||||
|
|||||||
30
zod/create-a-schema-that-matches-on-any-object.md
Normal file
30
zod/create-a-schema-that-matches-on-any-object.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Create A Schema That Matches On Any Object
|
||||||
|
|
||||||
|
Typically when creating an object schema with Zod, you have to specify the keys
|
||||||
|
and their types that make up the object.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import {z} from 'zod'
|
||||||
|
|
||||||
|
const objectSchema = z.object({ id: z.string() })
|
||||||
|
|
||||||
|
const obj = objectSchema.parse({ id: 1, type: 'user' })
|
||||||
|
//=> { id: 1 }
|
||||||
|
|
||||||
|
objectSchema.parse({ _id: 1, _type: 'user' })
|
||||||
|
//=> ZodError
|
||||||
|
```
|
||||||
|
|
||||||
|
If, however, you want a generic object schema that is ostensibly only checking
|
||||||
|
that the thing is an object and then allows any and all key-value pairs, you
|
||||||
|
can use the [`passthrough()`](https://github.com/colinhacks/zod#passthrough)
|
||||||
|
function.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import {z} from 'zod'
|
||||||
|
|
||||||
|
const anyObjectSchema = z.object({}).passthrough()
|
||||||
|
|
||||||
|
const obj = anyObjectSchema.parse({ id: 1, type: 'user' })
|
||||||
|
//=> { id: 1, type: 'user' }
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user