销毁深度嵌套的枚举,我必须键入每个项目吗?

问题描述 投票:1回答:1

我有一个深层嵌套的对象,由于所有枚举都不存在于对象中,因此会出错。

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

typescript enums destructuring
1个回答
0
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.