Created
September 25, 2024 22:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Real-world usage: