首页 > 解决方案 > 破坏深度嵌套的枚举,我是否必须键入每个项目?

问题描述

我有一个深度嵌套的对象,由于对象中不存在所有枚举,因此遇到了错误。

在示例中,解构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 不在嵌套对象中,我不确定重构此代码的正确方法是什么。任何帮助表示赞赏

标签: typescriptenumsdestructuring

解决方案


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)

推荐阅读