TLDR: This article introduces the zod-sugar library: https://github.com/samuelkarani/zod-sugar
When building my newly released ai-sugar library, I came across a use case where I needed to create a zod schema from a value - instead of the usual case where you define your schema then parse your value with it. So I made I library for it and released it for the world on NPM.
Here's example of how it works:
import { createZod } from "zod-sugar";
const object = {
foo: "bar",
bar: 1,
baz: [1, 2, 3],
qux: { foo: "bar" },
}
const schema = createZod(object);
// schema is a ZodObject
const result = schema.safeParse(object);
// result.success === true
It works with common javascript values: null, undefined, boolean, number, bigint, string, symbol, array, object:
createZod(null) // ZodNull
createZod(undefined) // ZodUndefined
createZod(1) // ZodNumber
createZod("foo") // ZodString
createZod(false) // ZodBoolean
createZod(Symbol("foo")) // ZodSymbol
createZod(BigInt(1)) // ZodBigInt
createZod([1, 2, 3]) // ZodArray
createZod({ foo: "bar", baz: 1 }) // ZodObject
createZod({
string: "bar",
number: 1,
array: [1, 2, 3],
bigint: BigInt(9007199254740991),
object: {
number: 0,
boolean: false,
object: {
string: "bar",
null: null,
[Symbol("foo")]: "bar",
},
array: ["1", "2", "3"],
},
undefined: undefined,
}) // ZodObject
To install it simply:
npm install zod-sugar
yarn add zod-sugar
pnpm install zod-sugar
Links
AI Sugar is the related library where these functions are used internally to work with AI APIs: https://github.com/samuelkarani/ai-sugar
Github link: https://github.com/samuelkarani/zod-sugar
NPM link: https://www.npmjs.com/package/zod-sugar
Top comments (0)