带Schema初始化Drizzle ORM客户端遇TypeScript类型错误求助
Drizzle ORM TypeScript类型报错解决建议
问题代码
实体定义(schema.ts)
// schema.ts export const users = pgTable('users', { id: serial('id').primaryKey(), email: varchar('email', {length: 256}).notNull(), });
Drizzle客户端初始化(db.server.ts)
// db.server.ts import {PostgresJsDatabase, drizzle} from 'drizzle-orm/postgres-js'; import postgres from 'postgres'; import * as schema from './schema'; const queryClient = postgres("postgres://..."); const db: PostgresJsDatabase = drizzle(queryClient, {schema});
报错信息
Type 'PostgresJsDatabase<typeof import("/app/db/schema")>' is not assignable to type 'PostgresJsDatabase'. The types of '_.schema' are incompatible between these types. Type 'ExtractTablesWithRelations<typeof import(/app/db/schema")> | undefined' is not assignable to type 'ExtractTablesWithRelations<Record<string, never>> | undefined'. Type 'ExtractTablesWithRelations<typeof import("/app/db/schema")>' is not assignable to type 'ExtractTablesWithRelations<Record<string, never>>'. Property 'users' is incompatible with index signature. Type '{ tsName: "users"; dbName: "users"; columns: { id: PgColumn<{ name: "id"; tableName: "users"; dataType: "number"; columnType: "PgSerial"; data: number; driverParam: number; notNull: true; hasDefault: true; enumValues: undefined; baseColumn: never; }, {}, {}>; email: PgColumn<...>; }; relations: never; primaryKey: An...' is not assignable to type '{ tsName: string; dbName: never; columns: never; relations: Record<string, Relation<string>>; primaryKey: AnyColumn[]; }'. Types of property 'dbName' are incompatible. Type 'string' is not assignable to type 'never'.ts(2322)
解决方法
方法1:让TypeScript自动推断类型(推荐)
去掉手动指定的PostgresJsDatabase类型声明,让TS自动根据传入的schema推断正确类型:
// db.server.ts import { drizzle } from 'drizzle-orm/postgres-js'; import postgres from 'postgres'; import * as schema from './schema'; const queryClient = postgres("postgres://..."); const db = drizzle(queryClient, {schema});
处理后db会自动获得包含users表的类型支持,可正常使用db.query.users.findMany()语法。
方法2:显式传入schema泛型参数
如果一定要手动指定类型,需要将你的schema类型作为泛型参数传给PostgresJsDatabase:
// db.server.ts import { PostgresJsDatabase, drizzle } from 'drizzle-orm/postgres-js'; import postgres from 'postgres'; import * as schema from './schema'; const queryClient = postgres("postgres://..."); const db: PostgresJsDatabase<typeof schema> = drizzle(queryClient, {schema});
问题根源
PostgresJsDatabase是泛型类型,不指定泛型参数时,默认使用空schema类型(Record<string, never>)。而你传入了包含users表的schema,导致类型不匹配。要么让TS自动推断,要么显式传入你的schema类型即可解决。
内容的提问来源于stack exchange,提问作者Janne
相关产品推荐
相关产品推荐

