Remove entry from enum typescript

Viewed 1188

I have an enum

export enum FloorTypeEnum {
  ENGINEERED_HARDWOOD = 'engineered_hardwood',
  SOLID_HARDWOOD = 'solid_hardwood',
  LAMINATE = 'laminate',
  LVT_VINYL = 'vinyl',
  CARPET = 'carpet',
  RUG = 'rug',
  CERAMIC = 'ceramic',
  CONCRETE = 'concrete',
  EPOXY = 'epoxy',
  FLOOR = 'floor', // deprecated value for backward compatibility
}

So at one place, I want to use this enum but remove the deprecated value (Floor). Is there any way we can do?

I have tried below

export type NewFloorTypeEnum = { 
    [key in Exclude<FloorTypeEnum , FloorTypeEnum .Floor> ]?: string
 };

I'm also maintaining an legacy enum

export enum LegacyFloorTypeEnum {
 FLOOR = 'floor'
}

But I'm confused on how to use that type. I want to use the key and value of the enum and return to frontend. Ultimate requirement is to get an enum which is equivalent to FloorTypeEnum - LegacyFloorTypeEnum. I don't want to create a new enum for new floor values.

Thanks

1 Answers

If I'm understanding you correctly, would something like this suffice?

export enum FloorTypeEnum {
  ENGINEERED_HARDWOOD = 'engineered_hardwood',
  SOLID_HARDWOOD = 'solid_hardwood',
  LAMINATE = 'laminate',
  LVT_VINYL = 'vinyl',
  CARPET = 'carpet',
  RUG = 'rug',
  CERAMIC = 'ceramic',
  CONCRETE = 'concrete',
  EPOXY = 'epoxy',
  FLOOR = 'floor', // deprecated value for backward compatibility
}

enum LegacyFloorTypeEnum {
  FLOOR = 'floor',
  NOT_FLOOR = 'not_floor'
 }

type NewFloorTypeEnum<T> = {
  [K in keyof T]: T[K];
}

// test case
const ok: NewFloorTypeEnum<FloorTypeEnum> = LegacyFloorTypeEnum.NOT_FLOOR;

I do not believe that Typescript can block FLOOR since they both share the same key/value (I may be wrong in this assumption so please take with a grain of salt). However, if you were to have a new value, in this is example I used NOT_FLOOR, it will throw an error if you try using a value in the enum that doesn't match the FloorTypeEnum.

Let me know if this does not meet your needs. Happy coding.

Related