Created
October 12, 2023 22:55
-
-
Save raiyansarker/9f6fd0a3c7ebb345b3218e6cd644ea08 to your computer and use it in GitHub Desktop.
This file contains 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} 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