Skip to content

Export enum as "object as const" #231

@jsskeen-utah

Description

@jsskeen-utah

In the Handbook: https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums

In modern TypeScript, you may not need an enum when an object with as const could suffice:

 const enum EDirection {
   Up,
   Down,
   Left,
   Right,
}
  
const ODirection = {
   Up: 0,
   Down: 1,
   Left: 2,
   Right: 3,
 } as const;
 
EDirection.Up;
           
(enum member) EDirection.Up = 0
 
ODirection.Up;
           
(property) Up: 0
 
// Using the enum as a parameter
function walk(dir: EDirection) {}
 
// It requires an extra line to pull out the values
type Direction = typeof ODirection[keyof typeof ODirection];
function run(dir: Direction) {}
 
walk(EDirection.Left);
run(ODirection.Right);

The biggest argument in favour of this format over TypeScript’s enum is that it keeps your codebase aligned with the state of JavaScript, and when/if enums are added to JavaScript then you can move to the additional syntax.


With NodeJS able to run TypeScript as long as you don't use things that are not real in JavaScript, it would be nice to support outputting enums as const objects.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions