skip to Main Content
enum Stage {
  STARTED = 1,
  COMPLETED
}

const SystemState = {
  Stage,
}

Is it possible to create a type by extracting the enum from the SystemState object i.e.

type stageType -> 1 | 2 (corresponds to the integral values of the Stage enum)

I’ve tried keyof typeof SystemState['Stage'] but this creates a string union type instead: "STARTED" | "COMPLETED".

2

Answers


  1. Try this. Type ValueOf maps each key of the enum to its value, and then unions those types together. So you can apply this utility type to your enum to get a union of its values:

    enum Stage {
      STARTED = 1,
      COMPLETED
    }
    
    const SystemState = {
      Stage,
    }
    
    type ValueOf<T> = T[keyof T];
    
    type StageType = ValueOf<typeof SystemState['Stage']>;
    
    Login or Signup to reply.
  2. Enums in Typescript are odd. From their syntax you would think they would behave similar to enums in other languages but when they’re transpiled they can produce some subtle bugs. Here is an article that talks about the possible issues: https://dev.to/ivanzm123/dont-use-enums-in-typescript-they-are-very-dangerous-57bh

    This article also describes an alternative to enums which looks like this:

    const Roles = {
      Admin: "admin",
      Writer: "writer",
      Reader: "reader"
    } as const;
    
    // Convert object key in a type
    type RoleKeys = typeof Roles[keyof typeof Roles]
    
    declare function hasAccess(role: RoleKeys): void;
    
    // Error!
    move('guest');
    
    // Great!
    move('admin');
    
    // Also great!
    move(Roles.Admin);
    

    I hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search