Home > Blockchain >  Element implicitly has an 'any' type because expression of type 'number' can
Element implicitly has an 'any' type because expression of type 'number' can

Time:11-08

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?

CodePudding user response:

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;
    …
})
  • Related