Search code examples
typescriptdynamictypescript-typingstyping

How to build dynamically a enum from array with Typescript


I want to build dynamically my typescript enum from a list of files, but I don't know how to do that.

Here is the code I wrote to get an array of value:

const fs = require('fs');

fs.readdir('./src/assets/icons', (err, files) => {
  const name = files
    .filter(file => file.match('.svg'))
    .map(fileFiltred => fileFiltred.replace('.svg', ''))

  console.log(name) // ["arrow-right", "home", "menu"...]
})

Can we build dynamically a typescript enum ? how ?

You think I have to write manually all icons name in my folder like below ?

enum iconName {
  HOME = 'home',
  ARROW_RIGHT = 'arrow-right',
  MENU = 'menu',
}

Thanks !


Solution

  • You can't create an actual typescript enum from just keys during runtime.

    How would you use it anyway? Enums are there to make sure you're not using any unknown values in your code that you did not previously define in your enum.

    To get that effect, you will need to have the enum somewhere in your project, your IDE can't magically know which icons are present in your directory.

    What you can do is, after you got the list of icon-names, check if those icon-names are present in your enum:

    let array: string[] = ["arrow-right", "home", "menu"];
    
    enum MyEnum {
    
        home = 'home',
        svg = 'svg'
    }
    
    array.forEach(element => console.log(MyEnum[element as MyEnum]))