admin管理员组文章数量:1362143
I recently migrated my Drizzle ORM setup from JavaScript to TypeScript, and now I'm facing an issue where the database schema is not recognized correctly.
Problem: When I try to query my database using Drizzle ORM, I get the following TypeScript error: Property 'users' does not exist on type '{}'.ts
Additionally, I am seeing this error when trying to assign drizzle to my db instance: Type 'DbQuery' is not assignable to type 'NodePgDatabase<Record<string, unknown>> & { $client: NodePgClient; }'. Type 'DbQuery' is missing the following properties from type 'NodePgDatabase<Record<string, unknown>>': _, query, $with, $count, and 10 more.
import * as schema from "../core/models/index";
import { Pool } from "pg";
import { drizzle } from "drizzle-orm/node-postgres";
import { environmentVar } from "./env";
class DatabaseConnection {
private static instance: DatabaseConnection | null = null;
private pool!: Pool;
private db: ReturnType<typeof drizzle> | null = null;
constructor() {
if (DatabaseConnection.instance) {
return DatabaseConnection.instance;
}
if (!environmentVar.DATABASE_URL) {
throw new Error("DATABASE_URL is not defined in the environment.");
}
this.pool = new Pool({
connectionString: environmentVar.DATABASE_URL,
max: 20,
idleTimeoutMillis: 60000 * 5,
connectionTimeoutMillis: 5000,
});
DatabaseConnection.instance = this;
}
getConnection() {
if (!this.db) {
this.db = drizzle(this.pool, { schema });
}
return this.db;
}
async close() {
if (this.pool) {
await this.pool.end();
console.log("Database pool closed.");
}
}
}
const dbInstance = new DatabaseConnection();
export const db = dbInstance.getConnection();
query code
import { db } from "../../config/database";
import { eq } from "drizzle-orm";
import { users } from "../core/models/index";
async function findUserByPhoneNumber(phoneNumber: string) {
const user = await db.query.users.findFirst({
where: eq(users.phoneNumber, phoneNumber),
});
return user;
}
What I've Tried So Far: ✅ Confirmed that my schema is correctly exported from ../core/models/index.ts
✅ Tried console.log(db.query)—it returns ["userStatus", "users"], so the schema does exist
✅ Manually imported users from the schema file instead of relying on db.query.users
✅ Changing database.ts to JavaScript (.js) makes it work without errors, but I want to use TypeScript
✅ Checked TypeScript configuration (tsconfig.json) to ensure strict mode is enabled
✅ Tried using as any as a workaround, but this is not a proper solution
Questions: Why does TypeScript not recognize my schema and show an error even though the code works?
How can I fix this issue so that I get proper TypeScript auto-completion for db.query.users in VS Code?
Is there a proper way to define db so that Drizzle ORM correctly infers the schema?
note that this was working fine when my entire project was in javascript. it was giving proper suggestions in vs code autocompletion and was working fine.
I recently migrated my Drizzle ORM setup from JavaScript to TypeScript, and now I'm facing an issue where the database schema is not recognized correctly.
Problem: When I try to query my database using Drizzle ORM, I get the following TypeScript error: Property 'users' does not exist on type '{}'.ts
Additionally, I am seeing this error when trying to assign drizzle to my db instance: Type 'DbQuery' is not assignable to type 'NodePgDatabase<Record<string, unknown>> & { $client: NodePgClient; }'. Type 'DbQuery' is missing the following properties from type 'NodePgDatabase<Record<string, unknown>>': _, query, $with, $count, and 10 more.
import * as schema from "../core/models/index";
import { Pool } from "pg";
import { drizzle } from "drizzle-orm/node-postgres";
import { environmentVar } from "./env";
class DatabaseConnection {
private static instance: DatabaseConnection | null = null;
private pool!: Pool;
private db: ReturnType<typeof drizzle> | null = null;
constructor() {
if (DatabaseConnection.instance) {
return DatabaseConnection.instance;
}
if (!environmentVar.DATABASE_URL) {
throw new Error("DATABASE_URL is not defined in the environment.");
}
this.pool = new Pool({
connectionString: environmentVar.DATABASE_URL,
max: 20,
idleTimeoutMillis: 60000 * 5,
connectionTimeoutMillis: 5000,
});
DatabaseConnection.instance = this;
}
getConnection() {
if (!this.db) {
this.db = drizzle(this.pool, { schema });
}
return this.db;
}
async close() {
if (this.pool) {
await this.pool.end();
console.log("Database pool closed.");
}
}
}
const dbInstance = new DatabaseConnection();
export const db = dbInstance.getConnection();
query code
import { db } from "../../config/database";
import { eq } from "drizzle-orm";
import { users } from "../core/models/index";
async function findUserByPhoneNumber(phoneNumber: string) {
const user = await db.query.users.findFirst({
where: eq(users.phoneNumber, phoneNumber),
});
return user;
}
What I've Tried So Far: ✅ Confirmed that my schema is correctly exported from ../core/models/index.ts
✅ Tried console.log(db.query)—it returns ["userStatus", "users"], so the schema does exist
✅ Manually imported users from the schema file instead of relying on db.query.users
✅ Changing database.ts to JavaScript (.js) makes it work without errors, but I want to use TypeScript
✅ Checked TypeScript configuration (tsconfig.json) to ensure strict mode is enabled
✅ Tried using as any as a workaround, but this is not a proper solution
Questions: Why does TypeScript not recognize my schema and show an error even though the code works?
How can I fix this issue so that I get proper TypeScript auto-completion for db.query.users in VS Code?
Is there a proper way to define db so that Drizzle ORM correctly infers the schema?
note that this was working fine when my entire project was in javascript. it was giving proper suggestions in vs code autocompletion and was working fine.
Share Improve this question asked Apr 1 at 13:23 UNRIVALLEDKINGUNRIVALLEDKING 4565 silver badges22 bronze badges1 Answer
Reset to default 2You need to pass your schema definition when declaring the type of your db
variable so TypeScript knows about your schema types:
class DatabaseConnection {
private db: ReturnType<typeof drizzle<typeof schema>> | null = null;
// ^^^^^^^^^^^^^ pass the schema type here
}
The Drizzle documentation examples are able to use TypeScript's type inference to work out the types, but you are explicitly declaring the type of the db
variable, so you need to explicitly pass the schema type as well.
It's possible to work this out backwards by looking at the types around the drizzle()
constructor:
// we're passing a schema property to the function
drizzle({schema});
// driver.d.ts
// There is a `TSchema` generic listed here
export declare function drizzle<
TSchema extends Record<string, unknown> = Record<string, never>,
TClient extends Client = Client
>(...params: [
TClient | string
] | [
TClient | string,
DrizzleConfig<TSchema> // <-- TSchema is referenced here
] | [
(DrizzleConfig<TSchema> & ({
connection: string | Config;
} | {
client: TClient;
}))
]): LibSQLDatabase<TSchema> & {
$client: TClient;
};
// utils.d.ts: DrizzleConfig<TSchema>
// The TSchema type is inferred or defined by the `schema` property on `DrizzleConfig`
export interface DrizzleConfig<
TSchema extends Record<string, unknown> = Record<string, never>
> {
logger?: boolean | Logger;
schema?: TSchema;
casing?: Casing;
}
// That tells us we can pass the type of the `schema` as the first generic:
type db_type = ReturnType<drizzle<typeof schema>>;
本文标签:
版权声明:本文标题:javascript - Why does Drizzle ORM with TypeScript not recognize my schema and show missing properties in VS Code? - Stack Overfl 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743882979a2555538.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论