How can I get the Typescript return type of a drizzle statement?

// How can I type the return type of this function?
export function selectUserIncludingToken(userId: User["id"]): ?? {
return db
.select()
.from(eghlTokens)
.rightJoin(users, eq(eghlTokens.userId, users.email))
.where(eq(users.id, userId))
.orderBy(desc(eghlTokens.createdAt))
.limit(1);
}
// How can I type the return type of this function?
export function selectUserIncludingToken(userId: User["id"]): ?? {
return db
.select()
.from(eghlTokens)
.rightJoin(users, eq(eghlTokens.userId, users.email))
.where(eq(users.id, userId))
.orderBy(desc(eghlTokens.createdAt))
.limit(1);
}
5 Replies
rphlmr ⚡
rphlmr ⚡2mo ago
2 possibilities. - no types and let TypeScript inference do it - await before return, then the type is just an object
rphlmr ⚡
rphlmr ⚡2mo ago
If you want the type infered from selectUserIncludingToken, you can use some TypeScript utils: https://drizzle.run/hb9tdgrc9h53vh08dc6ahm2b
async function getUserById(id: User["id"]) {
return (await db.select().from(users).where(eq(users.id, id)).limit(1)).at(0)
}

type UserById = Awaited<ReturnType<typeof getUserById>>
async function getUserById(id: User["id"]) {
return (await db.select().from(users).where(eq(users.id, id)).limit(1)).at(0)
}

type UserById = Awaited<ReturnType<typeof getUserById>>
cusx
cusx2mo ago
@Raphaël M (@rphlmr) ⚡ thannks for the response. unfortunately I can't use await because I'm writing statements that I can later use in various db.batch calls. So for now, I'll have to rely on Typescript inference, and turn off the eslint explicit return type rule. 😅
rphlmr ⚡
rphlmr ⚡2mo ago
Oh ok. Then it could be
async function getUserById(id: User["id"]) {
return db.select().from(users).where(eq(users.id, id)).limit(1))
}

type UserById = Awaited<ReturnType<typeof getUserById>>[number]
async function getUserById(id: User["id"]) {
return db.select().from(users).where(eq(users.id, id)).limit(1))
}

type UserById = Awaited<ReturnType<typeof getUserById>>[number]
I am on my mobile so 😅 maybe I am wrong
francis
francis2mo ago
I ended up writing a utility to do this. I can't tell if this stupid or not:
export type DbRecord<Type> =
Type extends PgTableWithColumns<infer T>
? PgSelectBase<T["name"], GetSelectTableSelection<Type>, "single">["_"]["result"][0]
: never;
export type DbRecord<Type> =
Type extends PgTableWithColumns<infer T>
? PgSelectBase<T["name"], GetSelectTableSelection<Type>, "single">["_"]["result"][0]
: never;
update, it was stupid, just use typeof myTable.$inferSelect
Want results from more Discord servers?
Add your server