I’m trying to implement database abstraction in my project (Honojs, Drizzle ORM, PostgreSQL) with complete TypeScript support.
I’m facing an issue while passing a column name in a query to the abstraction function where I’m using generic types
Here is my current setup:
export type DbTable = UserTable | ClientTable | ServiceTable | InvoiceTable | InvoiceFileTable;
export type NewDbRecord = NewUser | NewClient | NewService | NewInvoice | NewInvoiceFile;
export type DbRecord = User | Client | Service | Invoice | InvoiceFile;
Here is the function where the issue occurs:
export const getRecordByField = async <k extends keyof DbRecord>(
table: DbTable,
field: k,
value: DbRecord[k]
) => {
const respData = await db.select().from(table).where(eq(table[field], value));
return respData[0];
};
When I try to use this function:
async function findUserByEmail(emailValue: string) {
return await getRecordByField(users, 'email', emailValue);
}
I’m getting the following error:
Argument of type ‘”email”‘ is not assignable to parameter of type ‘”createdAt” | “updatedAt”‘.ts(2345)
It seems that only createdAt and updatedAt are recognized as valid keys of DbRecord.
How can I modify the types so that all fields (like email) are available when querying? Is there a solution to make this work with generics?
user27367455 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.