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

0

322
Views
El elemento tiene implícitamente un tipo 'cualquiera' porque la expresión del tipo 'número' no se puede usar para indexar el tipo '{}'

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?

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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