From 036a61fc40d3d142f8146bc2ff19aa0c34f13ccc Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 6 Sep 2022 21:40:10 -0700 Subject: [PATCH] Add Check If An Object Is Empty With Zod as a JavaScript TIL --- README.md | 3 +- .../check-if-an-object-is-empty-with-zod.md | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 javascript/check-if-an-object-is-empty-with-zod.md diff --git a/README.md b/README.md index 11db12b..06267c5 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). -_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) diff --git a/javascript/check-if-an-object-is-empty-with-zod.md b/javascript/check-if-an-object-is-empty-with-zod.md new file mode 100644 index 0000000..2e90422 --- /dev/null +++ b/javascript/check-if-an-object-is-empty-with-zod.md @@ -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)