How do you get defined types for relational queries

If i have a relational query like this
const post = await db.query.posts.findFirst({
with: {
comments: true,
},
});
const post = await db.query.posts.findFirst({
with: {
comments: true,
},
});
How do i get the type of post as a defined type to use as a function parameter type for instance? in prisma land, i manually have to define types like
interface PostWithComments extends Post {
comments: Comment[];
}
interface PostWithComments extends Post {
comments: Comment[];
}
is there a better way to do this?
5 Replies
Piotrek
Piotrek16mo ago
type PostWithComments = typeof post; can work inference can be used in many places
jakeleventhal
jakeleventhalOP16mo ago
how would that include comments as a field? in theory, there should be 2 different types
// Should have `comments` field
const post = await db.query.posts.findFirst({
with: {
comments: true,
},
});

// Should NOT have `comments` field
const post = await db.query.posts.findFirst({});
// Should have `comments` field
const post = await db.query.posts.findFirst({
with: {
comments: true,
},
});

// Should NOT have `comments` field
const post = await db.query.posts.findFirst({});
NinjaBunny
NinjaBunny16mo ago
i’m not sure if this would work but you could do something like this possibly
import { InferModel } from “drizzle-orm”;
//import tables

export type PostWithComment = InferModel<typeof Post, “select”> & InferModel<typeof Comment, “select”>;
import { InferModel } from “drizzle-orm”;
//import tables

export type PostWithComment = InferModel<typeof Post, “select”> & InferModel<typeof Comment, “select”>;
this might be what you’re looking for if you don’t want to create the type yourself @jakeleventhal
Piotrek
Piotrek16mo ago
In his case it would actually be something like that:
import { InferModel } from “drizzle-orm”;
//import tables

export type PostWithComments = InferModel<typeof Post, “select”> & {comments: InferModel<typeof Comment, “select”>[] };
import { InferModel } from “drizzle-orm”;
//import tables

export type PostWithComments = InferModel<typeof Post, “select”> & {comments: InferModel<typeof Comment, “select”>[] };
By inferring the return type for the query It would also be updated with your schema, contrary to what the example above does But you'd have to export this type from below the query Do what's better for you
jakeleventhal
jakeleventhalOP16mo ago
yeah so at the end of the day, you still have to manually define your types
Want results from more Discord servers?
Add your server