Skip to content

Instantly share code, notes, and snippets.

@raiyansarker
Created October 12, 2023 22:55
Show Gist options
  • Save raiyansarker/9f6fd0a3c7ebb345b3218e6cd644ea08 to your computer and use it in GitHub Desktop.
Save raiyansarker/9f6fd0a3c7ebb345b3218e6cd644ea08 to your computer and use it in GitHub Desktop.
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment