typescripttypeszod

How do I create a zod object with dynamic keys?


We can create Zod object that validates an object against the keys that are defined in the schema, but I only want to validate if the key is a string not if the key == something

In typescript we can achieve this by using

Record<string, string>;

But in zod, I tried this one

const data = z.object({
  [z.string()]: z.string(),
});

But it's not working


Solution

  • You're looking for z.record which can be used like:

    const data = z.record(z.string(), z.string());