Skip to content

Instantly share code, notes, and snippets.

@raiyansarker
Created October 12, 2023 22:55
Show Gist options
  • Select an option

  • Save raiyansarker/9f6fd0a3c7ebb345b3218e6cd644ea08 to your computer and use it in GitHub Desktop.

Select an option

Save raiyansarker/9f6fd0a3c7ebb345b3218e6cd644ea08 to your computer and use it in GitHub Desktop.

Revisions

  1. raiyansarker created this gist Oct 12, 2023.
    40 changes: 40 additions & 0 deletions typetozod.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    import {z} from "zod"

    type Implements<Model> = {
    [key in keyof Model]-?: undefined extends Model[key]
    ? null extends Model[key]
    ? z.ZodNullableType<z.ZodOptionalType<z.ZodType<Model[key]>>>
    : z.ZodOptionalType<z.ZodType<Model[key]>>
    : null extends Model[key]
    ? z.ZodNullableType<z.ZodType<Model[key]>>
    : z.ZodType<Model[key]>;
    };

    export function implement<Model = never>() {
    return {
    with: <
    Schema extends Implements<Model> & {
    [unknownKey in Exclude<keyof Schema, keyof Model>]: never;
    }
    >(
    schema: Schema
    ) => z.object(schema),
    };
    }

    // usage
    export type UserModel = {
    id: string
    email: string | null
    name: string
    firstName: string
    createdAt: Date
    }

    export const UserCreateSchema = implement<Omit<UserModel, "createdAt" | "id">>().with({
    email: z.string().email().nullable(),
    name: z.string(),
    firstName: z.string(),
    });

    export type UserCreatePayload = z.infer<typeof UserCreateSchema>