z.object().passthrough() not working with objects like Buffer
See original GitHub issueThanks for Zod!
Perhaps I am using this incorrectly, or missed something in the docs. I wanted to use a zod schema to parse an object containing a field that points to a Buffer
, more generally an object that implements Reader
(Buffer
does), but that detail isn’t important for this. I didn’t expect native support for Buffer
, so I figured I could use z.object({ ... }).passthrough()
, checking for the methods on Buffer
I cared about, but then passing through the whole object to keep the internals working.
What seems to happen is that I get back an object that has the bytes()
function, but the rest of the fields do not passthrough. So fundamentally, it seems that passthrough()
isn’t working for this case, unless i’m using it incorrectly.
Here is a reproduction using Deno:
import * as z from "https://cdn.skypack.dev/zod@^3";
import { Buffer } from "https://deno.land/std@0.125.0/io/buffer.ts";
const FooSchema = z.object({
bar: z.string(),
// stream is a Buffer, but passthrough all fields
stream: z.object({
bytes: z.function(),
}).passthrough(),
});
const throws = FooSchema.parse({
bar: "fizz",
stream: new Buffer(new Uint8Array(4).buffer),
});
console.log("typeof Buffer: ", typeof new Buffer(new Uint8Array(4).buffer));
// this throws because another method has been stripped that bytes() uses internally
console.log("throws.stream.bytes(): ", throws.stream.bytes());
Issue Analytics
- State:
- Created 2 years ago
- Comments:6
Top GitHub Comments
@TillaTheHun0 the type you need to handle this case is not possible to specify in TypeScript. So your best bet is it let the type be
any
but add an refinement to validate the input further.Looks great! I’ll go ahead and use that approach. I’ll go ahead and close this issue.