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:
@@ -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)
|
||||
|
||||
29
javascript/check-if-an-object-is-empty-with-zod.md
Normal file
29
javascript/check-if-an-object-is-empty-with-zod.md
Normal 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)
|
||||
Reference in New Issue
Block a user