Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to dynamically generate enums on TypeScript based on Object Keys?

Tags:

typescript

I'm defining an object and I want to dynamically generate enum based on its keys, so I get IDE suggestions and do not call wrong keys.

const appRoutes = {
   Login,
   Auth,
   NotFound
} 

enum AppRoutes = {[Key in keyof appRoutes]: [keyof appRoutes]}
like image 712
Caio Amaral Corrêa Avatar asked Jan 06 '19 04:01

Caio Amaral Corrêa


People also ask

Can we create dynamic enum?

You can dynamically create source code by reading from the database and simply outputting the results in a format conducive to building an enum. However, it is impractical to create an enum at run time.

Can an enum be an object TypeScript?

Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.

Can enums have objects?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).


1 Answers

I use this workaround to convert the keys to a const key -> key object:

const { Login, Auth, NotFound } = {} as any
const appRoutes = {
  Login,
  Auth,
  NotFound
}

const AppRoutes = (() => ({
 ...Object.keys(appRoutes)
   .filter(k => isNaN(Number(k)))
   .reduce((acc, cur) => ({
     ...acc,
     [cur]: cur,
   }), {}),
} as  {
 [k in keyof typeof appRoutes]: k
}))()

console.info(AppRoutes)
// AppRoutes: {
//   Login: "Login";
//   Auth: "Auth";
//   NotFound: "NotFound";
// }
like image 101
Huan Avatar answered Oct 08 '22 14:10

Huan