drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
21.44k stars 484 forks source link

Add `InferEnum` type #2552

Open totigm opened 4 days ago

totigm commented 4 days ago

Add a generic utility type InferEnum to facilitate type inference for enums defined with pgEnum. This enhancement aligns with the existing InferSelectModel and InferInsertModel utilities, simplifying type definitions for enums in Drizzle ORM.

Proposed Changes

Addition of the InferEnum type: A generic type that infers the possible values of an enum defined with pgEnum. This does not affect the existing functionality of the ORM. It merely adds a new utility type that developers can choose to use.

export type InferEnum<T> = T extends { enumValues: readonly (infer U)[] }
  ? U
  : never;

Usage

Example before the change:

const status = pgEnum("status", ["pending", "completed", "cancelled"]);
type Status = (typeof status.enumValues)[number];

Example after the change:

const status = pgEnum("status", ["pending", "completed", "cancelled"]);
type Status = InferEnum<typeof status>;

Benefits