typescripttypescript-typings

Extending Enum in typescript


I was hoping to reuse certain values in enum. Any suggestions of how to achieve such functionality.

enum someEnum {
    a = 'Some String',
    b = 2,
};

enum extendedEnum {
    c = 'string',
    b = someEnum.b
}

type someEnumType<T extends someEnum> = T extends someEnum.a ? string :
    T extends someEnum.b ? number : never;

type extendedEnumType<T extends extendedEnum> =
    T extends extendedEnum.c ? string:          // Gives Error
    T extends extendedEnum.b ? number : never;  // Gives Error

Solution

  • Currently, You can't extend enum in TypeScript

    Another option is to use type:

    enum Color1 {
        Red = "Red",
        Green = "Green"
    }
    
    enum Color2 {
        Yellow = "Yellow",
        Blue = "Blue"
    }
    

    define a new type named Colors :

    type Colors = Color1 | Color2;
    

    Then you can use it as below :

    class AppComponent {
        public color: Colors;
        
        ngOnInit(): void {
          const Colors = { ...Color2, ...Color1 };
          this.color = Colors.Red; // Colors.Green or Colors.Yellow or Colors.Blue
        }
    }
    

    Stackblitz Here (Angular)

    Stackblitz Here (Typescript)