Search code examples
typescriptzod

Zod Record with default key


I am trying to create an object type like this in zod:

{
    default: string,
    [string]: string,
}

I have tried using z.union to combine z.object and z.record but it does not validate as what I expected.

const LocaleString = z.union([
  z
    .object({
      default: z.string(),
    })
    .required(),
  z.record(z.string()),
]);

LocaleString.safeParse({
  testing: 'abc',
}); 
/** 
* it will return `{ success: true, data: { testing: 'abc' } }`, 
* where I expect it to fail when the data is without default value
*/

Solution

  • I found out this and it works for my case.

    const LocaleString = z.object({
      default: z.string(),
    }).and(z.record(z.string()));
    
    LocaleString.safeParse({
      default: 'abc',
    }); // pass
    
    LocaleString.safeParse({
      en: 'abc',
    }); // fail
    
    LocaleString.safeParse({}); // fail
    
    LocaleString.safeParse({
      default: 'abc',
      en: 'abc',
    }); // pass