Created
October 17, 2024 17:17
-
-
Save betafcc/43f1f2602aa1543df893f562ceadebc7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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, ZodObject, ZodTuple } from 'https://deno.land/x/zod/mod.ts' | |
export type ToZod<T> = T extends string | |
? z.ZodString | |
: T extends number | |
? z.ZodNumber | |
: T extends boolean | |
? z.ZodBoolean | |
: T extends null | |
? z.ZodNull | |
: T extends readonly any[] | |
? ZodTuple<{ -readonly [K in keyof T]: ToZod<T[K]> }> | |
: T extends Record<string, any> | |
? ZodObject<{ [K in keyof T]: ToZod<T[K]> }> | |
: z.ZodAny | |
export const toZod = <T>(obj: T): ToZod<T> => { | |
if (typeof obj === 'string') return z.string() as ToZod<T> | |
else if (typeof obj === 'number') return z.number() as ToZod<T> | |
else if (typeof obj === 'boolean') return z.boolean() as ToZod<T> | |
else if (obj === null) return z.null() as ToZod<T> | |
else if (Array.isArray(obj)) | |
return z.tuple(obj.map(item => toZod(item))) as ToZod<T> | |
else if (typeof obj === 'object') | |
return z.object( | |
Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, toZod(v)])), | |
) as ToZod<T> | |
else return z.any() as ToZod<T> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment