销毁深度嵌套的枚举失去类型安全性:打字稿

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

我有一个深层嵌套的对象,该对象在解构后会失去类型安全性。

在示例中,已解构的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相对较新,因此希望在这里学习我做错了什么。

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.