Replies: 3 comments
-
I'm at the exact same point. In fact, I got about half way done making an example repo before finding yours. I was able to work around the type error by using |
Beta Was this translation helpful? Give feedback.
-
type ReplaceNullWithUndefined<T extends object> = {
[k in keyof T]: null extends T[k] ? Exclude<T[k], null> | undefined : T[k];
}; will replace nulls with undefined in the types. It can be added around export type User = ReplaceNullWithUndefined<z.infer<typeof InsertUserSchema>>; For me, this then gave me an error on my My only question at this point is does this break anything? All I'm messing with is the types, not the values, so I am still pushing a |
Beta Was this translation helpful? Give feedback.
-
Full question: Can a nullable text column be made editable in a typed way in a form, by way of a Zod schema derived from the Drizzle table schema?
Problem: the text field has a type mismatch and can't handle
null
values potentially coming from the database.I have a minimal example app repo here. The problem is that the schema (
createInsertSchema
fromdrizzle-zod
) types the column with 'string | null | undefined' but the form field component accepts nonull
.undefined
is ok though.This shows up in the editor's intellisense, or when
tsc
runs.SQL Schema (users):
https://github.com/febeling/nextjs14-shadcnui-zod-rhf-drizzle-testcase/blob/e60d74413837276c7a248db1330490f612770007/src/lib/schema.ts#L5-L15
Use in form:
https://github.com/febeling/nextjs14-shadcnui-zod-rhf-drizzle-testcase/blob/e60d74413837276c7a248db1330490f612770007/src/app/new/page.tsx#L63-L79
The warning:
https://github.com/febeling/nextjs14-shadcnui-zod-rhf-drizzle-testcase/blob/e60d74413837276c7a248db1330490f612770007/README.md?plain=1#L23-L38
There is a longer explanation in the README.
It includes this workaround, which can be applied per each input component:
https://github.com/febeling/nextjs14-shadcnui-zod-rhf-drizzle-testcase/blob/e60d74413837276c7a248db1330490f612770007/README.md?plain=1#L48-L56
Other components in the app are: Shadcn/ui form, react-hook-form, @hookform/resolvers, and others, but I believe the key parts are Zod and Drizzle ORM here.
Questions:
Is there a better solution than this workaround?
Can the drizzle-zod schema be "patched," so that in transforms the database type on the way from db to form, e.g. from
null
to undefined? (I do have found therefine
to transform on the way from form to db.)Beta Was this translation helpful? Give feedback.
All reactions