Last active
June 16, 2023 21:26
-
-
Save christophemarois/681789014f58e0e16fdc9da81ee5c578 to your computer and use it in GitHub Desktop.
zMapKeys.ts
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
// 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