colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Zod .partial() no longer able to use programmatically #3590

Open tlagnese opened 3 months ago

tlagnese commented 3 months ago

Apologies, I never post issues, very long-time lurker first time poster.

I've been previously using Zod 3.8.17 and decided we should upgrade to the latest. Upon upgrading, I noticed that .partial() expects an argument of Record<string | number, never> which I'll admit I don't fully understand, but is no longer assignable to { [index: string]: boolean }

It seems like this was done in favor to have exact definitions for the partial argument.

I think this is fine, but this is a breaking change is it not? In our use-case, we have subsets of required fields based on specific conditions, and previously it was working really well creating a programmatic object { [index: string]: boolean } that could then mark various fields required based on those conditions. Now it seems we have to know exactly what the object looks like in order to use .partial().

Example:

private getPartialObjectForSection(fieldConfiguration: FieldConfigurationSection, state: States): { [index:string]: boolean } {
  const requiredFieldsArray = getFieldsForStateOfTypeInSection(fieldConfigSection.fieldConfigurations, state, ValidationType.REQUIRED);
  constAllFieldsForSection = fieldConfigSection.fieldConfigurations.map(configurations => configuration.fieldName);
  const partialFieldsObject: { [index:string]: boolean } = {};

  for (const field of allFieldsForSection) {
    if (!requiredFieldsArray.find(requiredField => field === requiredField)) {
      partialFieldsObject[field] = true;
    }
  }

  return partialFieldsObject;
}

then this is followed up in various places with schema.partial(partialFieldsObject)

I know I'm not topping the charts of leetcode anytime soon, but is there an alternative way to achieve this?

3pleFly commented 2 months ago

Would you provide a stackblitz example, where you are properly showing the error you receive