Skip to content

Instantly share code, notes, and snippets.

@betafcc
Created October 17, 2024 17:17
Show Gist options
  • Select an option

  • Save betafcc/43f1f2602aa1543df893f562ceadebc7 to your computer and use it in GitHub Desktop.

Select an option

Save betafcc/43f1f2602aa1543df893f562ceadebc7 to your computer and use it in GitHub Desktop.

Revisions

  1. betafcc created this gist Oct 17, 2024.
    29 changes: 29 additions & 0 deletions toZod.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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>
    }