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]}
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.
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.
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).
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";
// }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With