我是Typescript的新手,我试图找出以下内容:
我有一个来自数据库的字段,可以包含DBSchemaDefinedOpts
上的任何值。但是,在UI上,我希望能够显示这些值的变体(它的完整或缩写版本),因此我想返回一个const对象,该对象将包括按每个DB可能返回值分组的变体(在optsList
)。
我想我当前的方法行得通,但是我想知道是否有什么方法可以以编程方式实现这一目标,而不必在optsList
上重复太多代码以得到更优雅的解决方案。我知道我无法在reduce
上使用DBSchemaDefinedOpts
函数(因为它不是数组),并且在尝试其他方法时会遇到不同的错误,但是我想用Typescript来实现(最好)或Javascript会像这样:
// Keep scrolling for "OptsMap" and "DBSchemaDefinedOpts" definition
export const optsList: OptsMap = DBSchemaDefinedOpts.reduce((all, curr) => {
all[curr] = {
full: UIOpts[curr],
abbr: UIOptsAbbr[curr]
};
}, {})
如果我要尝试这样的事情:
// Keep scrolling for "OptsMap" and "DBSchemaDefinedOpts" definition
const optsList = {} as OptsMap;
for(const opt in DBSchemaDefinedOpts) {
optsList[opt] = {
full: UIOpts[opt],
abbr: UIOptsAbbr[opt]
}
}
我收到以下错误:
On "optsList[opt]":
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'OptsMap'.
No index signature with a parameter of type 'string' was found on type 'OptsMap'.
On "UIOpts[opt]":
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof UIOpts'.
No index signature with a parameter of type 'string' was found on type 'typeof UIOpts'.
On "UIOptsAbbr[opt]":
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof UIOptsAbbr'.
No index signature with a parameter of type 'string' was found on type 'typeof UIOptsAbbr'.
这是我当前的代码(同样,它可以正常工作,它不是很优雅,如果选项继续增加,则很难维护):
export enum DBSchemaDefinedOpts {
DAY = 'DAY',
MONTH = 'MONTH',
YEAR = 'YEAR'
}
enum UIOpts {
DAY = 'Daily',
MONTH = 'Monthly',
YEAR = 'Yearly',
}
enum UIOptsAbbr {
DAY = 'daily',
MONTH = 'mthly',
YEAR = 'yrly',
}
type OptsMap = {
[k in DBSchemaDefinedOpts]: {
full: UIOpts;
abbr: UIOptsAbbr;
}
}
export const optsList: OptsMap = {
[DBSchemaDefinedOpts.MONTH]: {
full: UIOpts.MONTH,
abbr: UIOptsAbbr.MONTH
},
[DBSchemaDefinedOpts.YEAR]: {
full: UIOpts.YEAR,
abbr: UIOptsAbbr.YEAR
},
[DBSchemaDefinedOpts.DAY]: {
full: UIOpts.DAY,
abbr: UIOptsAbbr.DAY
}
};
我也不确定OptsMap
是输入optsList
的最佳方法。
谢谢!