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

381
Vistas
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'

I am using useRef, and accessing its child elements.

And I am getting this error.

Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'. No index signature with a parameter of type 'number' was found on type '{}'

The code is

const subCnt = useRef<HTMLDivElement>();

useEffect(()=>{

    if (!(subCnt.current?.children?.length! > 0)) return

    let lastChild: ReactNode = subCnt.current?.children;
    lastChild = lastChild[lastChild?.length - 1]; //Getting the error here
    ...
})

The Line I am getting the error is at lastChild = lastChild[lastChild?.length - 1];

Why is it showing this error?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your actual mistake is on the line before:

let lastChild: ReactNode = subCnt.current?.children;

I don't know why TypeScript doesn't complain, apparently the types are weirdly compatible, but they really ought not. The type of .children is HTMLCollection - and it contains all children, not only the last one, so the name is confusing as well.

The correct way to do it would be

useEffect(() => {
    const children: HTMLCollection | undefined = subCnt.current?.children;
    if (!children?.length) return;

    const lastChild: HTMLElement = children[children.length - 1];
    …
})

but you can actually simplify that by simply using .lastElementChild directly:

useEffect(() => {
    const lastChild: HTMLElement | undefined = subCnt.current?.lastElementChild;
    if (!lastChild) return;
    …
})
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