Here's how to create a Zod validator for that TypeScript type:
typescript Copy code
import { z } from 'zod';
const priceMovementObjSchema = z.intersection(
z.object({
meta: z.object({
created_at: z.string(),
transaction_id: z.number(),
}),
}),
z.record(
z.string(),
z.object({
price: z.number(),
shares: z.number(),
})
)
).refine(
(data) => !['meta'].includes(Object.keys(data).find(k => k !== 'meta') || ''),
{
message: "Dynamic keys cannot override 'meta' property"
}
);
// Type inference (should match your PriceMovementObj)
type PriceMovementObj = z.infer<typeof priceMovementObjSchema>;
However, there's a cleaner approach using passthrough():
typescript Copy code
const priceMovementObjSchema = z.object({
meta: z.object({
created_at: z.string(),
transaction_id: z.number(),
}),
}).passthrough().superRefine((data, ctx) => {
// Validate all other properties match the expected shape
Object.entries(data).forEach(([key, value]) => {
if (key !== 'meta') {
const result = z.object({
price: z.number(),
shares: z.number(),
}).safeParse(value);
if (!result.success) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Property '${key}' must have 'price' and 'shares' as numbers`,
path: [key],
});
}
}
});
});
Or using catchall() which is more concise:
typescript Copy code
const priceMovementObjSchema = z.object({
meta: z.object({
created_at: z.string(),
transaction_id: z.number(),
}),
}).catchall(
z.object({
price: z.number(),
shares: z.number(),
})
);
Usage example:
typescript Copy code
// Valid data
const validData = {
meta: {
created_at: "2024-01-01",
transaction_id: 123,
},
AAPL: {
price: 150.50,
shares: 100,
},
GOOGL: {
price: 2800.00,
shares: 50,
},
};
const result = priceMovementObjSchema.parse(validData); // ✓ Passes
The catchall() approach is likely the cleanest for your use case, as it explicitly handles the known meta property and applies validation to all other properties.