Home > Enterprise >  Typescript Convert Enum to Constant Class
Typescript Convert Enum to Constant Class

Time:11-18

How do I convert an Enum to a Constant Class like this, in Typescript? Currently using React Typescript, with functional components . This question is slightly different: TypeScript enum to object array

export enum ProductStatus {
  Draft = 1,
  Review = 2,
  Approved = 3,
  Rejected = 4,
  Billed = 5,
  Collected = 6,
  Unpayable = 7,
  WorkInProgress = 8,
  ReadyToReview = 9,
  NeedsRevision = 10,
  Failed = 11,
}

export const ProductStatus = {
  Draft: 1,
  Review: 2,
  Approved: 3,
  Rejected: 4,
  Billed: 5,
  Collected: 6,
  Unpayable: 7,
  WorkInProgress: 8,
  ReadyToReview: 9,
  NeedsRevision: 10,
  Failed: 11,
};

CodePudding user response:

loop throught the keys and use ethe reduce function

  const newConst = React.useMemo(() => {
    return Object.keys(ProductStatus).reduce((acc, key) => {
      if (isNaN(Number(key))) {
        acc[key] = ProductStatus[key];
      }
      return acc;
    }, {});
  }, []);

  console.log(newConst );

https://stackblitz.com/edit/react-ts-ivfxqw?file=App.tsx

CodePudding user response:

We can use Object.values to get the values from the enum and convert them to an object using reduce.

const ProductStatusObject = Object.values(ProductStatus)
  .filter((v): v is keyof typeof ProductStatus => typeof v !== "number")
  .reduce((p, c) => {
    p[c] = ProductStatus[c]
    return p
  }, {} as Record<keyof typeof ProductStatus, number>)

ProductStatusObject
// ^? Record<"Draft" | "Review" | "Approved" | ..., number>

As you may know, enums contain a mapping in both directions. We need to filter out the values which are not of type string to only get the keys of the enum. The filter callback also needs a type predicate to indicate to TypeScript that the resulting array only contains values of type keyof typeof ProductStatus.

The reduce method takes the elements of the array and assigns them as keys to an object using the corresponding enum value. I typed the object as Record<keyof typeof ProductStatus, number> to get a useful return type.

console.log(ProductStatusObject)

/*
{
  "Draft": 1,
  "Review": 2,
  "Approved": 3,
  "Rejected": 4,
  "Billed": 5,
  "Collected": 6,
  "Unpayable": 7,
  "WorkInProgress": 8,
  "ReadyToReview": 9,
  "NeedsRevision": 10,
  "Failed": 11
} 
*/ 

Playground

  • Related