You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Drizzle中定义自动填充的只读created_at列并实现可选类型推断?

在Drizzle中实现created_at字段插入时可选的类型推断

核心问题说明

你当前使用的$inferSelect是查询数据时的类型,由于created字段配置了数据库默认值,查询返回的记录必然包含该字段,所以类型推断为Date是符合数据库实际情况的。而你需要的是插入记录时的可选类型,应该使用Drizzle提供的另一种推断类型。

解决方案

1. 使用插入专属的推断类型

Drizzle的$inferInsert会自动识别字段的默认值配置,将对应字段推断为可选类型。修改你的类型定义:

export const user = pgTable('user', {
    id: text('id').primaryKey(),
    age: integer('age'),
    // ...其他字段
    created: timestamp('created', { withTimezone: true, mode: 'date' })
        .default(sql`now()`)
});

// 插入记录时用这个类型
export type UserInsert = typeof user.$inferInsert;

此时UserInsert的类型为:

type UserInsert = {
    id: string;
    age: number | null;
    // ...其他字段
    created?: Date; // 符合需求的可选类型
}

2. (不推荐)手动覆盖查询类型

如果确实需要让查询返回的类型中created为可选,可以通过类型工具手动调整,但这不符合数据库实际数据情况,不建议使用:

export type User = Omit<typeof user.$inferSelect, 'created'> & { created?: Date };

注意事项

不要给created字段添加.nullable(),这会让数据库允许该字段为null,和你“只读、自动填充”的需求冲突,默认值已经能保证插入时自动生成该字段的值。

内容的提问来源于stack exchange,提问作者opensas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 01:52:14