To create a Zod schema for the given TypeScript type PriceMovementObj2, follow this solution:
import { z } from "zod";
const PriceMovementObj2Schema = z.object({
meta: z.object({
created_at: z.string().refine((val) => !isNaN(Date.parse(val)), // Validates date string
transaction_id: z.number(),
}),
market: z.record(
z.object({
price: z.number(),
shares: z.number(),
})
),
});
Explanation:
-
meta Validation:
created_at: Uses z.string() combined with a refine to ensure it's a valid date string. The refinement checks if Date.parse() can convert it to a valid timestamp.
transaction_id: Validated as a number with z.number().
-
market Validation:
- Uses
z.record() to represent the dynamic keys.
- Each key's value is validated as an object with:
price: Validated as a number.
shares: Also validated as a number.
Key Notes:
-
ISO Date Validation: The refine check ensures created_at is a parseable date string (covers ISO 8601 and other formats). For strict ISO 8601 validation, replace the refine with:
created_at: z.string().datetime({ offset: true }) // Requires Zod 3.20+
(Note: .datetime() is available in Zod ≥v3.20.0; use a regex-based refinement if using an older version).
-
Dynamic Keys: z.record() handles arbitrary string keys in the market object while enforcing the structure of their values.
This schema ensures objects match the TypeScript type structure while providing runtime validation.