【发布时间】:2020-01-22 17:16:04
【问题描述】:
我有数据对象:
const data = [
{
type: 'soccer',
price: '$10'
},
{
type: 'running',
price: '$5'
},
{
type: 'hockey',
price: '$15'
}
]
我想将它转换为 key 为 item.type 的对象:
const parsedData = {
soccer: {
type: 'soccer',
price: '$10'
},
running: {
type: 'running',
price: '$5'
},
hockey: {
type: 'hockey',
price: '$15'
}
}
我已经用类型定义了枚举:enum GameTypes { 'soccer', 'running', 'hockey' }。当我尝试使用枚举作为对象的键时,我得到了错误:
元素隐式具有“any”类型,因为“GameTypes”类型的表达式不能用于索引“GameProducts”类型。
类型“GameProducts”.ts(7053) 上不存在属性“[GameTypes.lottery]”
完整代码:
enum GameTypes { 'soccer', 'running', 'hockey' }
type Game = {
type: GameTypes
price: string
}
type GameProducts = { [key in GameTypes]?: Game } | {}
const data: Array<Game> = [
{
type: 'soccer',
price: '$10'
},
{
type: 'running',
price: '$5'
},
{
type: 'hockey',
price: '$15'
}
]
// trying to format games in object
const formatGames: GameProducts = data.reduce((acc | {}, item) => {
if (!acc[item.type]) { // <-- error here
acc[item.type] = []
}
acc[item.type].push(item)
return acc
}, {})
我做错了什么?还有其他方法吗?
【问题讨论】:
标签: typescript enums