【发布时间】:2022-01-19 17:36:52
【问题描述】:
在这里做一个项目。我正在使用 Nextjs 和 Typescript。我有选项卡,在一个选项卡中,我通过了很多对象,我创建了一个 reduce 函数来对所有内容进行排序并将其推送到适当的类别中。我遇到了这个问题
类型“未定义”不能用作索引类型。
特别是在reduce函数内部的每个title(此处用cmets标记)下。
界面:
export interface ITimelineItem {
title?: string
subtitle?: string
date?: string
reference?: string
description?: string
skillSet?: string
reverse?: boolean
startYear?: string
endYear?: string
}
interface ITimeline {
items?: ITimelineItem[]
}
const TimeLine: React.FC<ITimeline> = ({ items = [] }) => {
const classes = useStyles()
const cat = items.reduce((item, { skillSet, title }) => {
if (!item[title!]) item[title] = []
// ^^^^^ ^^^^^
item[title].push(skillSet)
// ^^^^^
return item
}, {})
}
【问题讨论】:
-
您的示例充满了语法错误。请提供一个可重现的。另外,请考虑格式化。尝试使用ts playground
-
请...即使我们尝试修复编译器错误,给定的代码也不完整并且存在逻辑错误。请提供完整的功能,或者至少去掉不必要的部分。
标签: javascript typescript next.js