Comment

Comment by joshstrange

After trying enums in TS a long time back I also realized it was best to avoid them. Here is my solution to this:

    // filename: role.ts
    export const Role = {
        CUSTOMER: 'customer',
        ADMIN: 'admin',
        SYSTEM: 'system',
        STAFF: 'staff',
    } as const;
    type TRole = keyof typeof Role;
    export type TUserRole = typeof Role[TRole];

Using this structure I can reference any of my roles by `Role.CUSTOMER` and the value is `customer` because it's just a `Record<string, string>` at the end of the day. But I am able to type things by using my `TUserRole` so a function can required that the input be one of the values above. For me this is really clean and easy to use. Note the `type TRole` isn't exported as it's only an intermediary in this process, I could just as well name it `type temp` in all my files and never worry about conflicts.

This way I'm not spreading "special" strings all over my code (always a sign of code smell for me), I can changed everything at a central location, and it's valid JS (it's just an object).

EDIT: I know that `as const` seems unnecessary but I'm pretty sure it's needed for some reason, I whittled this down to the smallest/simplest code block I could and I just copy/paste this pattern whenever I need enum-like functionality.

parent joshstrange 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton