Created
September 29, 2023 23:04
-
-
Save christophemarois/512493fd182ce89627b4a48acb4e4ecd to your computer and use it in GitHub Desktop.
Zod Unique Array
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
/** Array where are elements are expected to be unique by a custom key */ | |
export function zUniqueArray< | |
ArrSchema extends z.ZodArray<z.ZodTypeAny, 'many'>, | |
UniqueVal, | |
>( | |
uniqueBy: (item: z.infer<ArrSchema>[number]) => UniqueVal, | |
schema: ArrSchema, | |
) { | |
return schema.superRefine((items, ctx) => { | |
const seen = new Set<UniqueVal>() | |
for (const [i, item] of items.entries()) { | |
const val = uniqueBy(item) | |
if (seen.has(val)) { | |
ctx.addIssue({ | |
code: z.ZodIssueCode.custom, | |
message: `Unique property validation failed`, | |
path: [i], | |
}) | |
} else { | |
seen.add(val) | |
} | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment