Created
October 12, 2023 22:55
-
-
Save raiyansarker/9f6fd0a3c7ebb345b3218e6cd644ea08 to your computer and use it in GitHub Desktop.
Revisions
-
raiyansarker created this gist
Oct 12, 2023 .There are no files selected for viewing
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 charactersOriginal 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>