使用Drizzle插入表时遇到TypeScript类型安全问题
问题:Drizzle插入数据时TypeScript类型报错
我定义了如下Drizzle schema:
export const Organization = pgTable( "Organization", { id: text("id").primaryKey().notNull(), name: text("name").notNull(), createdAt: timestamp("createdAt", { precision: 3, mode: "string" }) .defaultNow() .notNull(), updatedAt: timestamp("updatedAt", { precision: 3, mode: "string", }).notNull(), }, (table) => { return { name_key: uniqueIndex("Organization_name_key").using( "btree", table.name, ), }; }, );
执行插入查询时:
import * as schema from "../src/drizzle/schema"; import { Client } from "pg"; import { drizzle } from "drizzle-orm/node-postgres"; export const client = new Client({ connectionString: process.env.DATABASE_URL, }); export const db = drizzle(client, { schema }); await db.insert(Organization).values({ id: "68184833-8d03-41d6-95a2-4f23c4f097d6", name: "org", createdAt: new Date(), updatedAt: new Date(), });
TypeScript报错:
Object literal may only specify known properties, and 'id' does not exist in type '{ id: string | SQL<unknown> | Placeholder<string, any>; ...
用as any能规避报错,但不想放弃类型安全,请问哪里操作有误?
解决方案
问题根源是字段类型不匹配:
你在Schema里给createdAt和updatedAt设置了mode: "string",这表示Drizzle期望这两个字段的值是字符串类型(比如2024-05-20T12:34:56.789Z这样的ISO格式字符串),但插入时你传的是new Date()生成的Date对象,类型不匹配触发了TypeScript的类型检查。
由于TypeScript在对象类型校验中,只要有一个字段类型错误,就可能干扰整个对象的类型提示,所以才会出现看似id字段不存在的错误信息,实际问题出在时间字段上。
有两种解决方式:
方式1:插入时将Date转为字符串
把new Date()替换成new Date().toISOString(),生成符合要求的时间字符串:
await db.insert(Organization).values({ id: "68184833-8d03-41d6-95a2-4f23c4f097d6", name: "org", createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), });
方式2:修改Schema的时间字段配置
把时间字段的mode改成"date",这样Drizzle就会直接接受Date类型的值:
export const Organization = pgTable( "Organization", { id: text("id").primaryKey().notNull(), name: text("name").notNull(), createdAt: timestamp("createdAt", { precision: 3, mode: "date" }) .defaultNow() .notNull(), updatedAt: timestamp("updatedAt", { precision: 3, mode: "date", }).notNull(), }, (table) => { return { name_key: uniqueIndex("Organization_name_key").using( "btree", table.name, ), }; }, );
内容的提问来源于stack exchange,提问作者Adam A
相关产品推荐
相关产品推荐

