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. I came across this problem
Type 'undefined' cannot be used as an index type.
Specifically under every title
(marked with comments here) inside of the reduce function.
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
}, {})
}
Solution 1:
Since in ITimelineItem
title
is marked as optional, it can be undefined
, which cannot be used to index objects. To fix it, add a check for title
before using it as index.
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.
if (!item[title!]) item[title] = []