Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

385
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda