Replies: 1 comment
-
|
Yes, this is an intentional and documented aspect of Zod codecs: the Here's a concise example for your use case: // 1. Schema for raw DB row (all fields as strings)
const dbRowSchema = z.object({
id: z.number(),
label: z.string(),
date: z.string(), // ISO string from DB
});
// 2. Codec for date transformation
const stringToDate = z.codec(
z.string(),
z.date(),
{
decode: (iso) => new Date(iso),
encode: (date) => date.toISOString(),
}
);
// 3. Schema for your strongly typed object
const appRowSchema = z.object({
id: z.number(),
label: z.string(),
date: stringToDate, // Date object in your app
});
// Usage:
const rawRow = await fetchRowFromDb(); // unknown
const parsedRow = dbRowSchema.parse(rawRow);
const appRow = appRowSchema.parse({ ...parsedRow, date: parsedRow.date });
// Now appRow.date is a Date objectAlternatively, you can use For more details, see the official Zod codecs documentation and the API reference. This pattern is also discussed in related issues. If this answers your question, feel free to close the issue! If you need more details or examples, let me know. To reply, just mention @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Let's say I have a database (SQLite) that I am fetching data from. The schema is simple:
On the service side, I want to read this row and get a strongly typed object from it. Normally, I'd just do something like this:

However, let's say that I want to use a codec like the one in the documentation that transforms my ISO date text field into a
Dateobject. As mentioned in the documentation, this works fine if you already have the object strongly typed when it is passed todecode. However, seemingly by design, you can't do that if the object is of typeunknown—which myrowis (since we don't know the data shape from the query yet).As a result, this doesn't work:

And, since my conversion is using two different data types (

stringandDate), I can't do this, either:I had hoped that codecs would help me avoid using two schemas + a conversion method, but so far it doesn't seem like it can. Is this an expected limitation of codecs? What is the ideal way to handle this situation?
Beta Was this translation helpful? Give feedback.
All reactions