>我有数据对象:
const data = [
{
type: 'soccer',
price: '$10'
},
{
type: 'running',
price: '$5'
},
{
type: 'hockey',
price: '$15'
}
]
我想将其转换为键将是 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.lottery]"在类型"GameProducts".ts(7053(上不存在
完整代码:
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
}, {})
我做错了什么?还有其他方法可以做到吗?
有几个问题需要解决:
游戏- 产品未定义,可能应该由游戏取代
- 游戏产品是映射到数组而不是简单对象
- 为了让化简器理解代码并适当地 lint,使用不可变代码会更容易,如下所示
- 使用需要使用转译器的映射
GameTypes['some_value']
来确认代码。
enum GameTypes { 'soccer', 'running', 'hockey' }
type Game = {
type: GameTypes
price: string
}
type GameProducts = { [key in GameTypes]?: Game[] };
const data: Array<Game> = [
{
type: GameTypes['soccer'],
price: '$10'
},
{
type: GameTypes['running'],
price: '$5'
},
{
type: GameTypes['hockey'],
price: '$15'
}
]
// formatting games object
const formatGames: GameProducts = data.reduce((acc: GameProducts, item) => {
if (!acc[item.type]) {
acc[item.type] = [];
}
acc[item.type] = [
...(acc[item.type] || []),
item
];
return acc
}, {});
console.log(formatGames);
您也可以选择使用:
enum GameTypes { Soccer = 'soccer', Running = 'running', Hockey = 'hockey' }
const data: Array<Game> = [
{
type: GameTypes.Soccer,
price: '$10'
}
]
或者更简单的解决方案:
type GameTypes = 'soccer' | 'running' | 'hockey';
const data: Array<Game> = [
{
type: 'soccer',
price: '$10'
}
]
这同样可以正常工作。