typescript 使用默认键的Zod记录

fd3cxomn  于 2023-03-31  发布在  TypeScript
关注(0)|答案(1)|浏览(106)

我尝试在zod中创建一个这样的对象类型:

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

我试过使用z.union来合并z.objectz.record,但它并没有像我预期的那样有效。

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
*/
pcww981p

pcww981p1#

我发现了这一点,它对我的案子很有效。

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',
}); // fail

相关问题