Circular Reference Error when Using Self-Reference in Table Definition with Drizzle-ORM

I encountered an error while defining a PostgreSQL table using Drizzle-ORM. The issue arises when attempting to create a self-referencing array column that references the primary key of its own table. The error message suggests that there is an issue with type inference possibly due to the self-reference.

import { createId } from "@paralleldrive/cuid2";
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
import { z } from "zod";
import {
  pgTable,
  varchar,
  timestamp,
  jsonb,
  integer,
} from "drizzle-orm/pg-core";
import { sql } from "drizzle-orm";

const course = pgTable("course", {
  id: varchar("id")
    .primaryKey()
    .$defaultFn(() => createId()),
  name: varchar("name").unique().notNull(),
  description: varchar("description").notNull(),
  image_url: varchar("image_url"),
  content_object: jsonb("content_object"),
  version: integer("version").default(1).notNull(),
  dependencies_courses: varchar("dependencies_courses").array().references(() => course.id),
  
  created_at: timestamp("created_at", {
    precision: 3,
  })
    .default(sql`CURRENT_TIMESTAMP(3)`)
    .notNull(),
  updated_at: timestamp("updated_at")
    .default(sql`CURRENT_TIMESTAMP(3)`)
    .$onUpdateFn(() => new Date())
    .notNull(),
});

const insertCourseSchema = createInsertSchema(course);
interface NewCourse extends z.infer<typeof insertCourseSchema> {}

const selectCourseSchema = createSelectSchema(course);

interface Course extends z.infer<typeof selectCourseSchema> {}

export { course, insertCourseSchema, selectCourseSchema };

export type { NewCourse, Course };


'course' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

Expected Behavior:
I expect to define a self-referencing column (dependencies_courses) that can store an array of course IDs, referencing the id column of the same course table without causing a type inference issue.
Was this page helpful?