create exportable types for frontend services
I feel like I'm missing something fundamental. I can create my Drizzle schema
user = mysqlTable('user', {id: ....});
and use them in my queries to get data back. I want to return my result set to the frontend as {id: 1, ...}
and strongly type the API return value. I thought that doing export type UserModel = InferModeltype<typeof user>
would do that, but I get a type that looks like MySQLTableWithColumns....
instead of simply {id: number....}
. What am I missing? I see how Drizzle keeps my queries type safe, but how can I leverage it to make sure consumers of my services use proper types? I feel like everyone is doing this, that it's super easy, and I'm just dumb right now.10 Replies
You want to provide types with your rest api response to the frontend? or do you want to provide validation for insert endpoints?
Both ideally, but I was speaking about types with my rest api to the frontend. I was also thinking that I could use drizzle-zod to validate - on the frontend and backend (when a request comes in), but I haven't gotten that far in my thinking.
Right now, being able to give my frontend developers types/interfaces is the primary goal.
You can import types to the front end no problem. It will get tree shaken by the compiler
As long as it's just types
The problem is that the
userSchema
shows up as a type of MySQLTableWIthColumns...
and not something simple like interface UserModel {id: number, ...}
.Also, there's a new way to infer types:
export type User = typeof user.$inferSelect
Interesting. I saw that, but I was using (insert)
export type UserModel = InferModelType<typeof user, 'insert'>
and it wasn't working, but when I switched to the $inferInsert
it works great. Was the InferModelType
just wrong?IDK where did you get that
InferModelType
Is that drizzle?Yeah, the examples show using
InferModel
but in my IDE it said that was deprecated to use InferModelType
, it's from drizzle-orm
version 0.29.1I think you mean
InferInsertModel
but.... as I look at the deprecation - yep
dammit
thanks - I'm a bone head.
I appreciate the help. I can't believe that I looked at that wrong. I knew that I had to be doing something dumb.