Skip to content

Instantly share code, notes, and snippets.

@AspireOne
Created September 25, 2024 22:09
Show Gist options
  • Save AspireOne/29c56d7536414bc05f17ebd73713b4a0 to your computer and use it in GitHub Desktop.
Save AspireOne/29c56d7536414bc05f17ebd73713b4a0 to your computer and use it in GitHub Desktop.
a Zod utility function to make specific fields inside an existing schema nullable. Just provide a (typesage) array of fields to make nullable.
import { z } from "zod";
type NullableKeys<T, K extends keyof T> = Omit<T, K> & { [P in K]: T[P] | null };
export function makeFieldsNullable<T extends z.ZodTypeAny, K extends keyof z.infer<T>>(
schema: T,
keys: K[],
): z.ZodType<NullableKeys<z.infer<T>, K>> {
return schema.transform((data) => {
const result = { ...data };
keys.forEach((key) => {
if (result[key] === undefined) {
result[key] = null;
}
});
return result as NullableKeys<z.infer<T>, K>;
});
}
@AspireOne
Copy link
Author

AspireOne commented Sep 25, 2024

Real-world usage:

function baseUpdateActivitySchema(i18n: I18n) {
  const base = baseActivitySchema(i18n).extend({
    id: z.number().min(0, { message: i18n._(t`ID aktivity je povinné (interní chyba)`) }),
  });

  // Make fields that are normally optinal nullable, so that the server can differentiate
  // between empty and null values (e.g. not changed, vs removed).
  return makeFieldsNullable(base, ["date", "time", "maxParticipants", "address"]);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment