DEV Community

Discussion on: What is Zod and what does it bring over typescript type definitions

Collapse
 
ingosteinke profile image
Ingo Steinke, web developer • Edited

I discovered Zod as Astro recommends or expects it when using MDX front matter content collections with TypeScript, and I found it very useful. Despite the "single source of truth", I still have more than a single place to edit my type definitions, e.g.

// content.config.ts (Zod)
icon: z.enum(['book', 'blogpost']).default('book').optional(),
Enter fullscreen mode Exit fullscreen mode

and

// Book.tsx (TypeScript JSX)
interface CardProps {
  icon?: 'book'|'blogpost';
Enter fullscreen mode Exit fullscreen mode

I wondered if there is an elegant way to avoid this data duplication. Update: I eventually found out about type inference like this ...

// Book.tsx
import type { z } from 'zod';
import { CardSchema } from './content.config';

export type CardProps = z.infer<typeof CardSchema>;
Enter fullscreen mode Exit fullscreen mode

... but still struggled to make it work.