zod-get
v1.0.1
Published
**zod-get** is a **tiny** TypeScript library that provides a safe and convenient way to traverse and validate JSON-like structures using [Zod](https://github.com/colinhacks/zod) schemas. It allows you to safely navigate through nested objects with unknown
Downloads
4
Readme
zod-get
zod-get is a tiny TypeScript library that provides a safe and convenient way to traverse and validate JSON-like structures using Zod schemas. It allows you to safely navigate through nested objects with unknown structures and obtain values while ensuring the values conform to specified types.
Features
- Safely traverse through nested objects in a JSON-like structure.
- Validate values against Zod schemas.
- Retrieve values from the structure while ensuring type safety.
- Gracefully handle undefined or invalid properties.
Installation
You can install zod-get via npm:
npm install zod-get
Usage
- Import the
get
function:
import { get } from 'zod-get';
import * as z from 'zod';
- Safely traverse and validate the JSON-like structure:
const examplePayload = {
"company": {
"name": "TechCorp",
"departments": {
"marketing": {
"team_lead": "Alice",
"members": ["Bob", "Carol", "David"]
},
}
}
};
// Traverse the tree without needing to validate every part
// (you will only need `?.` if noUncheckedIndexedAccess is enabled)
const teamLeadName = get(examplePayload)?.company?.departments?.marketing?.team_lead?.(z.string());
console.log(teamLeadName); // Output: "Alice"
// Oops, this doesn't exist, but we don't get any runtime error:
const doesntExist = get(examplePayload).company.departments.does_not_exist.team_lead(z.string());
console.log(doesntExist); // Output: undefined
// zod-get won't let you use a value without validating it:
const teamLead: string = get(examplePayload).company.departments.does_not_exist.team_lead;
// ^ TypeScript: Type 'Unvalidated' is not assignable to type 'string'.
Why
In Typescript, the unknown
type is a helpful alternative to any
, because it requires the developer
to check the value before using it, but it can be cumbersome to use for deeply nested structures, since
you can't use a common JS idiom:
// This is fine in JS, but if examplePayload is `unknown` in TS, you can't do this.
const isTeamLeadAlice = examplePayload?.company?.departments?.marketing?.team_lead === "Alice";
One TypeScript alternative is to use any
, but it could cause issues:
// Oops teamLead is supposed to be a string, but it's undefined. Or maybe it's a number? Who knows?
const teamLead: string = (examplePayload as any)?.company?.departments?.does_not_exist?.team_lead;
So the safer alternative is to use a zod schema, which you should do most of the time if you care about type safety!
// Oof!
const schema = z.object({
company: z.object({
departments: z.object({
marketing: z.object({
team_lead: z.string(),
}),
}),
}),
});
const parsed = schema.safeParse(examplePayload);
const teamLead: string | undefined = parsed.success
? parsed.data.company.departments.marketing.team_lead
: undefined;
That works for most cases but sometimes it can be pretty verbose, especially for a one-off deep access like this.
API
get(data: unknown): Unvalidated
The get
function returns an "Unvalidated" type for arbitrary, yet safe, navigation through a JSON-like
structure. "JSON-like" refers to scalar data that is potentially nested. In other words, zod-get won't
allow function calls and may not work with other odd scenarios. Though it should be possible to call a
function if you validate it first.
data
: The JSON-like structure to traverse.
Unvalidated
The Unvalidated
type represents a arbitrarily-traversable type unassignable to non-unknown/any types. Calling
an Unvalidated
with a zod schema "unwraps" the value, validating it against the supplied schema. If it passes
the underlying value at the property path is returned. Otherwise, undefined is returned.
Contributing
Contributions are welcome! Please feel free to open issues or submit pull requests to improve the library.
To install dependencies:
bun install
To run:
bun run index.ts
This project was created using bun init
in bun v1.0.33. Bun is a fast all-in-one JavaScript runtime.
License
This project is licensed under the MIT License - see the LICENSE file for details.