我有一个深层嵌套的对象,该对象在解构后会失去类型安全性。
在示例中,已解构的const { position, func }
均为any
类型。当我检查索引[表] [索引]时,可以看到所有3种的正确类型(索引,表和索引)
enum Index {
BY_DEFAULT = "bydefault",
}
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
Typescript相对较新,因此希望在这里学习我做错了什么。
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)