• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

335
Views
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 3 years ago · Juan Pablo Isaza
1 answers
Answer question

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 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error