admin管理员组

文章数量:1126318

I need to validate an object with a field that may be bigint, number, or undefined.

const IdNumberSchemaNullable = z.union([
    z.number().nonnegative().optional(), // For floating-point numbers and integers
    z.bigint().nonnegative(),  // For big integers (BigInt type)
    z.undefined()
]);
const OrderDetailsSchema = BaseSchema.extend({
    _t: z.literal('my_something'),
    id_test: z.IdNumberSchemaNullable,

All works, except when an object does not contain id_test field - I get following exception:

TypeError: Cannot read properties of undefined (reading '_parse')
    at ZodObject._parse (file:////node_modules/zod/lib/index.mjs:2526:37)
    at ZodObject._parseSync (file:////node_modules/zod/lib/index.mjs:649:29)
    at ZodDiscriminatedUnion._parse (file:////node_modules/zod/lib/index.mjs:3010:27)
    at ZodDiscriminatedUnion._parseSync (file:////node_modules/zod/lib/index.mjs:649:29)
    at file:////node_modules/zod/lib/index.mjs:2373:29
    at Array.map (<anonymous>)
    at ZodArray._parse (file:////node_modules/zod/lib/index.mjs:2372:38)
    at ZodArray._parseSync (file:////node_modules/zod/lib/index.mjs:649:29)
    at ZodArray.safeParse (file:////node_modules/zod/lib/index.mjs:679:29)
    at ZodArray.parse (file:////node_modules/zod/lib/index.mjs:660:29)

本文标签: javascriptHow to express bigint or number or undefined using Zod SchemaStack Overflow