typescript - 破坏深度嵌套的枚举,我是否必须键入每个项目?
问题描述
我有一个深度嵌套的对象,由于对象中不存在所有枚举,因此遇到了错误。
在示例中,解构const { position, func }
的都是 type any
。当我检查 index[table][index] 时,我可以看到所有 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 不在嵌套对象中,我不确定重构此代码的正确方法是什么。任何帮助表示赞赏
解决方案
type
需要为索引值创建A。在下面的示例中,我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)
推荐阅读
- python-3.x - Python:manager.Queue() 与 asyncio。如何解决死锁?
- android - 在 Android Studio 中使用 Fragment 在工具栏中显示和隐藏菜单图标
- python - 为什么存储计算字段 odoo10 在数据库中为空
- reactjs - 如何在 TypeScript 中编写具有依赖道具的反应组件?
- load-balancing - 有没有办法根据百分比值配置流量负载分布
- go - 为什么通道阻塞时select语句会抛出错误
- angular - 以下错误似乎是针对行为主体任意抛出的:TS2322: Type 'string | null' 不可分配给类型 'string'
- poco - 无法在 OSX Big Sur 上构建 Poco 1.10.1
- python - 如何比较两个 zip 文件中的文件是否完全相同?
- android - Android MediaRecorder 每次都没有被初始化