[英]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.我正在尝试将许多常量导出为数组,稍后我可以导入这些常量和 map。 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.我不能将它们全部放在一个 object 中并导出它们,因为我正在使用 generics(OptionInterface)并且我希望保留类型验证。
Currently, I export each object as a named export and then export all as an array.目前,我将每个 object 导出为命名导出,然后将所有导出为数组。 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, eg:如果我尝试删除导出的数组并只导入所有元素,例如:
import * as elems from 'Elements';
and then use it as in doSomething, I get an error:然后像在doSomething中一样使用它,我得到一个错误:
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?任何想法如何实现将所有常量导出为数组但同时保持输入?
import * as elems
will probably give you an object like this: import * as elems
可能会给你一个 object 像这样:
{
"elemOne": ...
"elemTwo": ...
...
}
Try using Object.values
to get an array with the exported values:尝试使用Object.values
获取具有导出值的数组:
import * as elems from 'Elements';
const doSomething = () => {
Object.values(elems).map(...)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.