Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

385
Vistas
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
  }, {})
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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] = []
about 4 years ago · Juan Pablo Isaza Denunciar

0

This is saying you cannot use title as the index value in item[**title**] because title might not exist. to fix this, you can use the Non-null Assertion operator !.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda