-
I'm trying to create a generic getItem function that can accept any database schema in TypeScript using Drizzle ORM. Here's the code snippet I've attempted:
However, I'm encountering the following TypeScript error on the return statement:
It seems to be related to mismatched types between the inferred schema and the expected return type. I'd like guidance on how to properly create a generic function that can accept any Drizzle ORM schema and return the corresponding inferred type correctly. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
I believe you don't need to be so specific in your generic, I think this should work: async function getItem<T extends AnyPgTable>( // <-- If you're using pg
schema: T,
): Promise<T["$inferSelect"]> {
const query = db.select().from(schema).limit(1);
const [item] = await query;
return item;
} |
Beta Was this translation helpful? Give feedback.
-
Is there any way to infer types from optional joins in a generic function? type JoinConfig = {
table: PgTable
on: SQL
}
const getTableWithLeftJoins = <T extends unknown[]>(
baseTable: PgTable,
joins: JoinConfig[]
) => {
const db = clientDb(getJwt)
const query = db.select().from(baseTable)
joins.forEach(join => {
query.leftJoin(join.table, join.on)
})
return query.execute() as unknown as Promise<T>
} Also.. where? async function getItem<T extends PgTable>(
schema: T,
where: SQL<unknown> | ((aliases: Assume<GetSelectTableSelection<T>, ColumnsSelection>) => SQL<unknown> | undefined) | undefined
): Promise<T["$inferSelect"] | undefined> {
const db = clientDb(getJwt)
const query = db.select().from(schema).limit(1).where(where)
const [item] = await query
return item
} |
Beta Was this translation helpful? Give feedback.
I believe you don't need to be so specific in your generic, I think this should work: