Amjad sibili
Amjad sibili

Reputation: 1149

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

Upvotes: 57

Views: 52040

Answers (1)

Souperman
Souperman

Reputation: 9836

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

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

Upvotes: 101

Related Questions