Skip to content

Instantly share code, notes, and snippets.

@christophemarois
Last active June 16, 2023 21:26
Show Gist options
  • Save christophemarois/681789014f58e0e16fdc9da81ee5c578 to your computer and use it in GitHub Desktop.
Save christophemarois/681789014f58e0e16fdc9da81ee5c578 to your computer and use it in GitHub Desktop.
zMapKeys.ts
// Type inference does not work yet
export function zMapKeys<
Shape extends z.ZodRawShape,
T extends z.ZodObject<Shape>,
Key extends keyof Shape,
MapFn extends <T extends Key>(v: Shape[T], k: T) => PropertyKey,
>(schema: T, renameMap: Record<Key, PropertyKey | MapFn>) {
const keys = Object.keys(schema.shape) as Key[]
return schema.transform((input) => {
let output: Record<PropertyKey, any> = {}
for (const k of keys) {
let targetKey: PropertyKey = k as PropertyKey
if (typeof renameMap[k] === 'function') {
targetKey = (renameMap[k] as MapFn)(input[k]!, k)
}
if (typeof renameMap[k] === 'string') {
targetKey = renameMap[k] as PropertyKey
}
output[targetKey]
}
return output
})
}
const out = zMapKeys(z.object({ a: z.string(), b: z.string() }), { b: 'c' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment