1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-07 09:08:01 +00:00

Add Check If An Object Is Empty With Zod as a JavaScript TIL

This commit is contained in:
jbranchaud
2022-09-06 21:40:10 -07:00
parent 704e6f2f6d
commit 036a61fc40
2 changed files with 31 additions and 1 deletions

View File

@@ -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).
_1240 TILs and counting..._
_1241 TILs and counting..._
---
@@ -385,6 +385,7 @@ _1240 TILs and counting..._
- [Character Codes from Keyboard Listeners](javascript/character-codes-from-keyboard-listeners.md)
- [Check Classes On A DOM Element](javascript/check-classes-on-a-dom-element.md)
- [Check If A Number Is Positive Or Negative](javascript/check-if-a-number-is-positive-or-negative.md)
- [Check If An Object Is Empty With Zod](javascript/check-if-an-object-is-empty-with-zod.md)
- [Check If Something Is An Array](javascript/check-if-something-is-an-array.md)
- [Check The Password Confirmation With Yup](javascript/check-the-password-confirmation-with-yup.md)
- [Compare The Equality Of Two Date Objects](javascript/compare-the-equality-of-two-date-objects.md)

View File

@@ -0,0 +1,29 @@
# Check If An Object Is Empty With Zod
Zod is a schema validation library. It can be used to check all sorts of
properties about the data moving through our system.
Let's look at how to implement a common type of check -- is this object empty?
```javascript
import {z} from 'zod';
const emptyObjectSchema = z.object({}).strict();
const isEmpty = (obj: object): boolean => {
const result = emptyObjectSchema.safeParse(obj);
return result.success;
}
isEmpty({});
//=> true
isEmpty({ hello: 'world' });
//=> false
```
This `emptyObjectSchema` _strictly_ defines the schema as an empty object
(`{}`). Without the [`strict()`](https://github.com/colinhacks/zod#strict)
part, we'd be allowing an object with key-value pairs to quietly pass the
validation.
[source](https://twitter.com/jbrancha/status/1565728882082385920)