· 1 min read
#029
Better Way to Write Your Enum in Drizzle Schema
Did you write your Drizzle Enum with an array of string?
export const statusEnum = pgEnum("status", ["available", "reserved", "rented"]);
I used to think the above method was fine until I slow down and think for a better way.
The better way is Typescript enum.
Below is an example and why I think this approach is better:
export enum BookStatus {
AVAILABLE = "available",
RESERVED = "reserved",
RENTED = "rented",
}
export const statusEnum = pgEnum("status", BookStatus);
This is because:
- Single Source of Truth: Your enum value are now from BookStatus Enum only. If you write it as string, you probably have to rewrite the enum string again when you want to use it somewhere else.
- Maintainability: Code is cleaner and more easily to maintain due to the enum declare at one place only. The whole codebase should refer here only.
Enforce it with one line in Claude.md
In order to ensure your coding agent follow this pattern for enum declaration, you can add below into your CLAUDE.md.
Drizzle
pgEnum: define a TSenumthenpgEnum('name', Enum)— never inline string arrays.
I hope it is helpful.