简体   繁体   English

类型“undefined”不能用作索引类型。 Typescript

[英]Type 'undefined' cannot be used as an index type. Typescript

working on a project here.在这里做一个项目。 I am using Nextjs and Typescript. I have tabs, in one tab I am getting a lot of objects passed through, I made a reduce function to sort and push everything in its proper category.我正在使用 Nextjs 和 Typescript。我有选项卡,在一个选项卡中我得到了很多对象,我做了一个 reduce function 来排序并将所有内容推送到适当的类别中。 I came across this problem我遇到了这个问题

Type 'undefined' cannot be used as an index type.类型“undefined”不能用作索引类型。

Specifically under every title (marked with comments here) inside of the reduce function.特别是在 reduce function 内的每个title下(此处标有注释)。

interface:界面:

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
  }, {})
}

Since in ITimelineItem title is marked as optional, it can be undefined , which cannot be used to index objects.由于在ITimelineItemtitle被标记为可选,它可以是undefined ,它不能用于索引对象。 To fix it, add a check for title before using it as index.要修复它,请在将其用作索引之前添加对title的检查。

if (title !== undefined && !item[title]) item[title] = []

You can also use non-null assertion operator here, but the code will break if the title is actually undefined and it basically defeats the purpose of TS here.你也可以在这里使用非空断言操作符,但是如果title实际上是undefined的,代码就会中断,这基本上违背了 TS 的目的。

if (!item[title!]) item[title] = []

This is saying you cannot use title as the index value in item[**title**] because title might not exist.这表示您不能使用title作为item[**title**]中的索引值,因为title可能不存在。 to fix this, you can use the Non-null Assertion operator !要解决此问题,您可以使用非空断言运算符! . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM