Johnny.sh

Better Enums in Typescript

Enums in typescript are cursed. This is not up for discussion. What is up for discussion is a good alternative.

Here’s a nice implementation:

const UserRoles = ["staff", "admin", "user"] as const;

type UserRole = typeof UserRoles[number];

type User = {
  role: UserRole;
}

This gives us rpetty much everything we’d need:

  • Iteration through the array of values (for example, for populating a dropdown).
  • A value-constrained string type constrained to the enum values
  • Type completion and everything else we’d possibly want from an enum

Alternative way:

const UserRoles = {
  "staff": "staff",
  "admin": "admin",
  "user": "user"
} as const

type UserRole = typeof UserRoles[typeof keyof UserRoles];
Last modified: May 04, 2023
/about
/uses
/notes
/talks
/projects
/podcasts
/reading-list
/spotify
© 2024