Infer type for relational query
Is there anyway to infer the type of a relational queries result? For example if I have a user who makes posts which has comments. I have a relational query which gets me all my users, their posts and their comments nested. Is there a way to infer that type? Currently constructing the type myself from the tables in the schema.
7 Replies
@Dbeg I have achieved this by moving the query inside of a function, then using typescript's ReturnType helper.
I am using this pattern in nextjs api routes
Oh ok yes that works! Thanks π
You probably were doing this but for anyone else, the return type of the async func would be a union type of the type | undefined wrapped in a promise. So this is what I did to get the exact type:
@mcgrealife Is this what you also had to do? or did I just do some longer for no reason. π€£
Ah yes, I should have mentioned this too!
Your Awaited implementation is actually cleaner than mine!, but same idea to unwrap the promise, yes!
I have been using NonNullable anytime I use the type βΒ it is much better to use it directly in the custom type definition! Thanks for the tip @Dbeg π
u guys did it wrongly
let's say i'm using postgres driver
once you have defined your schema and the relations in the schema, the type inference will work
the key point here is to ensure you declare your drizzle instance with
typeof schema
as the generic type
well, by right the inference should work automatically without the above, i'm not sure if it's because of we split up the schema into different filesAh I see. I answered a different question. Confirmed that my relation queries definitely infer their own return types (without manual type annotation)!
I answered from the context of nextjs api files. Where the
export
type keyword can only be used in the outer scope. So I wrap the db query in a function defined in the outer scope, invoke that function from the inner scope, but export it's return type in the outer scope.
Thanks CayterThanks @Cayter So I do have that and I realise I poorly worded my question.
I actually was wondering if there was something along the lines of drizzle infer type from a schema method but for relations querties.
so say I have a post table
I can do something like this
I now have the exact type for Post that I can use, in say props for a component.
Is there a way I could get a type for what is inferred? @mcgrealife method actually worked as well where i just take the inferred return type. Did not see anything in the docs about it get an explicit type for what a relation query could return.
FWIW, a dedicated type for inferring model with relations is to be done - https://github.com/drizzle-team/drizzle-orm/issues/695