我有一个深层嵌套的对象,由于所有枚举都不存在于对象中,因此会出错。
在示例中,已解构的const { position, func }
均为any
类型。当我检查索引[表] [索引]时,可以看到所有3种的正确类型(索引,表和索引)
enum Index {
BY_DEFAULT = "bydefault",
BY_ID = "byid",
}
enum Table {
DELIVERY = 'delivery',
}
const indexes = {
[Table.DELIVERY]: {
[Index.BY_DEFAULT]: { position: 1, func: (data: { index: number }) => data.index + 5 },
}
};
const get = async (data: any, table: Table, index: Index) => {
const { position, func } = indexes[table][index]
func(data)
}
get({ index: 1 }, Table.DELIVERY, Index.BY_DEFAULT)
打字稿3.7.3
这里的错误是因为BY_ID不在嵌套对象中,所以我不确定重构该代码的正确方法是什么。任何帮助表示赞赏
A type
需要为索引值创建。在下面的示例中,我为其定义了一个type
并将[Index.BY_DEFAULT]
的值强制转换为所创建的类型。
enum Index {
BY_DEFAULT = "bydefault",
}
enum Table {
DELIVERY = 'delivery',
}
type IndexedValueType = { position: number, func: (data: { index: number }) => number }
const indexes = {
[Table.DELIVERY]: {
[Index.BY_DEFAULT]: <IndexedValueType>{ position: 1, func: (data: { index: number }) => data.index + 5 },
}
}
const get = async (data: any, table: Table, index: Index) => {
const { position, func } = indexes[table][index]
func(data)
}
get({ index: 1 }, Table.DELIVERY, Index.BY_DEFAULT)