Search code examples
typescriptwebpackecmascript-6module-export

ES6 typescript import all exported constants as an array


I'm trying to export many constants that I can later import and map through as an array. I can't put them all in one object and export them, because I'm using generics (OptionInterface) and I wish to keep the type validations.

Currently, I export each object as a named export and then export all as an array. The problem is that another developer might not know he must add a new element to the exported array.

An example:

//ElemSettings.tsx
export interface ElemProps<OptionInterface = any> {
  title: string,
  key: string,
  options: OptionsInterface[] 

export interface SpecialOption {
 s1: string,
 s2: number
}


//Elements.tsx - what I wish to export
export const elemOne: ElemProps {
  title: 'element One',
  key: elemOne'
  options: [1,2,3]
}

export const elemTwo: ElemProps {
  title: 'element Two',
  key: elemTwo'
  options: [1,2,3]
}

export const elemThree: ElemProps<SpecialOption> {
  title: 'element Two',
  key: elemTwo'
  options: [{s1:'one',s2:1},{s1:'two',s2:2}]
}

//This is how I export now
export const elems: Array<ElemProps> =
  [elemOne, elemTwo, elemThree]



//user.tsx
import { elems } from 'Elements';

const doSomething = () => { 
      elems.map(...)
}

If I try to remove the exported array and just import all the elements, e.g:

import * as elems from 'Elements';

and then use it as in doSomething, I get an error:

Property 'map' does not exist on type 'typeof import("Elements")'.

Any ideas how can I achieve exporting all constants as an array but keep the typing as well?


Solution

  • import * as elems will probably give you an object like this:

    {
        "elemOne": ...
        "elemTwo": ...
        ...
    }
    

    Try using Object.values to get an array with the exported values:

    import * as elems from 'Elements';
    
    const doSomething = () => { 
      Object.values(elems).map(...)
    }