How to infer connection type in TypeScript?

I'd like this function can receive transaction connection from another function, or can use normal db connection as default, so how to define type for this parameter?
No description
1 Reply
Sillvva
Sillvva2w ago
I think this is what you're looking for. I use postgres, so I'm not 100% on this.
import * as schema from "$server/db/schema";
import { type MySqlTransaction } from "drizzle-orm/mysql-core";
import { drizzle, MySql2Database, type MySql2PreparedQueryHKT, type MySql2QueryResultHKT } from "drizzle-orm/mysql2";

export const db = drizzle(connection, { schema });

export type Databse = MySql2Database<typeof schema>;
export type Transaction = MySqlTransaction<MySql2QueryResultHKT, MySql2PreparedQueryHKT, typeof schema>;
import * as schema from "$server/db/schema";
import { type MySqlTransaction } from "drizzle-orm/mysql-core";
import { drizzle, MySql2Database, type MySql2PreparedQueryHKT, type MySql2QueryResultHKT } from "drizzle-orm/mysql2";

export const db = drizzle(connection, { schema });

export type Databse = MySql2Database<typeof schema>;
export type Transaction = MySqlTransaction<MySql2QueryResultHKT, MySql2PreparedQueryHKT, typeof schema>;
With this, the type you're looking for is Database | Transaction If you have the RQBv2 beta installed, it would look like this:
import * as schema from "$server/db/schema";
import { relations } from "$server/db/relations";
import { type MySqlTransaction } from "drizzle-orm/mysql-core";
import { drizzle, MySql2Database, type MySql2PreparedQueryHKT, type MySql2QueryResultHKT } from "drizzle-orm/mysql2";

export const db = drizzle(connection, { schema, relations });

export type Databse = MySql2Database<typeof schema, typeof relations>;
export type Transaction = MySqlTransaction<MySql2QueryResultHKT, MySql2PreparedQueryHKT, typeof schema, typeof relations>;
import * as schema from "$server/db/schema";
import { relations } from "$server/db/relations";
import { type MySqlTransaction } from "drizzle-orm/mysql-core";
import { drizzle, MySql2Database, type MySql2PreparedQueryHKT, type MySql2QueryResultHKT } from "drizzle-orm/mysql2";

export const db = drizzle(connection, { schema, relations });

export type Databse = MySql2Database<typeof schema, typeof relations>;
export type Transaction = MySqlTransaction<MySql2QueryResultHKT, MySql2PreparedQueryHKT, typeof schema, typeof relations>;

Did you find this page helpful?