1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-10 18:48:02 +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

@@ -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)