While working on FocusYar, my Next.js project, I had a confusing issue: a goal existed in the database, but the application couldn't retrieve it correctly.
The problem was a type mismatch.
I was working with an ID that arrived as a string, while my Zod schema expected a number.
Before
const id = "123"; The Fix
import { z } from "zod"; const schema = z.object({ id: z.coerce.number(), }); z.coerce.number() attempts to convert the input to a number before validation.
This is especially useful when handling URL parameters and query strings.
A More Strict Version
If the ID must be a positive integer, I can validate that requirement too:
const schema = z.object({ id: z.coerce.number().int().positive(), }); One important detail: coercion and validation are different things. Converting a value to a number doesn't automatically make it a valid ID.
My Takeaway
When debugging a problem, I shouldn't immediately assume the database or query is broken. I should inspect the data, check its type, and follow it through the application.
I'm learning to solve problems by understanding their causes instead of just fixing their symptoms.
![Why Object.keys(user) Returns string[], Not (keyof User)[]: TypeScript Means It](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2q4w48b9bzs43tynyhsf.png)
