How to keep a TypeScript interface in sync with a Zod schema?

400 Views Asked by At

I have an existing project primarily written in TypeScript where we originally had no runtime validations for our data. As we're expanding our API and also have JavaScript users, I've decided to introduce Zod to validate our data at runtime.

Example

import { z } from 'zod';

interface MyData {
  name: string;
  age: number;
  isStudent?: boolean;
}

const MyDataSchema = z.object({
  name: z.string(),
  age: z.number(),
  isStudent: z.boolean().optional()
});

The challenge I'm facing is keeping the MyData interface and the MyDataSchema in sync. Every time I update the TypeScript interface, I have to manually update the Zod schema. This manual process is error-prone and can lead to inconsistencies.

I tried using satisfies z.ZodType<MyTypescriptType> (example below), but it doesn't handle optional types well.

const MyDataSchema = z.object({
  name: z.string(),
  age: z.number(),
  isStudent: z.boolean().optional()
}) satisfies z.ZodType<MyData>;

Is there an efficient way to enforce synchronization between a TypeScript interface and a Zod schema? Ideally, I'd like an approach where updating the interface would either automatically update the schema or at least throw an error if they're out of sync.

0

There are 0 best solutions below