Estoy usando useRef y accediendo a sus elementos secundarios.
Y estoy recibiendo este error.
El elemento tiene implícitamente un tipo 'cualquiera' porque la expresión de tipo 'número' no se puede usar para indexar el tipo '{}'. No se encontró ninguna firma de índice con un parámetro de tipo 'número' en el tipo '{}'
el codigo es
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 ... })
La línea en la que obtengo el error es lastChild = lastChild[lastChild?.length - 1];
¿Por qué muestra este error?
Su error real está en la línea antes:
let lastChild: ReactNode = subCnt.current?.children;
No sé por qué TypeScript no se queja, aparentemente los tipos son extrañamente compatibles, pero realmente no deberían. El tipo de .children
esHTMLCollection
, y contiene todos los elementos secundarios, no solo el último, por lo que el nombre también es confuso.
La forma correcta de hacerlo sería
useEffect(() => { const children: HTMLCollection | undefined = subCnt.current?.children; if (!children?.length) return; const lastChild: HTMLElement = children[children.length - 1]; … })
pero en realidad puede simplificar eso simplemente usando .lastElementChild
directamente:
useEffect(() => { const lastChild: HTMLElement | undefined = subCnt.current?.lastElementChild; if (!lastChild) return; … })