ES6 打字稿将所有导出的常量导入为数组

ES6 typescript import all exported constants as an array

我正在尝试导出许多常量,稍后我可以将这些常量作为数组导入和映射。 我不能将它们全部放在一个对象中并导出它们,因为我正在使用泛型 (OptionInterface) 并且我希望保留类型验证。

目前,我将每个对象导出为命名导出,然后将所有对象导出为数组。问题是另一个开发人员可能不知道他必须向导出的数组添加一个新元素。

一个例子:

//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(...)
}

如果我尝试删除导出的数组并只导入所有元素,例如:

import * as elems from 'Elements';

然后像在 doSomething 中那样使用它,我得到一个错误:

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

有什么想法可以实现将所有常量导出为数组,同时保持键入吗?

import * as elems 可能会给你这样一个对象:

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

尝试使用 Object.values 获取包含导出值的数组:

import * as elems from 'Elements';

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