Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Mecanografiado con React, infiere el tipo de matriz pasada como prop

tengo este componente:

 import React from 'react' export interface IForEachProps { each: any[] children: <T>(item: T, index: number) => JSX.Element given?: boolean key?: (item: any) => any } export const For: React.FC<IForEachProps> = ({ each, children, key, given = true }) => { if (!given) return null return ( <> {each.map((item, index) => ( <React.Fragment key={key ? key(item) : index}>{children(item, index)}</React.Fragment> ))} </> ) }

No he tenido éxito en mis intentos de inferir el tipo de each accesorio, ya que podría ser cualquier matriz. Lo que quiero, mirando el ejemplo a continuación, es que el compilador deduzca de la matriz de entrada que el parámetro en la devolución de llamada es, de hecho, una cadena.

 const list: string[] = ['hello'] <For each={list}> {(item) => ( <div>{item.length}</div> )} </For>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Resuelto. Tuve que convertir el componente en un componente de función para poder usar genéricos correctamente.

 import React from 'react' export interface IForEachProps<T> { each: Array<T> children: (item: T, index: number) => JSX.Element given?: boolean key?: (item: any) => any } export function For<T>({ each, children, key, given = true }: IForEachProps<T>) { if (!given) return null return ( <> {each.map((item, index) => ( <React.Fragment key={key ? key(item) : index}>{children(item, index)}</React.Fragment> ))} </> ) }
about 4 years ago · Juan Pablo Isaza Report

0

Seguro que no funciona. TS ve que each: any[] . Eso significa "olvida todo lo que sepas sobre ese tipo". Para que esto funcione, debe proporcionar tipos genéricos para esta interfaz. Por lo tanto, obligará a TS a encontrar el tipo exacto de esta matriz:

 export interface IForEachProps<Item> { each: Array<Item> children: (item: Item, index: number) => JSX.Element given?: boolean key?: (item: Item) => string | number

También recomiendo encarecidamente evitar "cualquier" tipo. Siempre arruina la idea central del texto mecanografiado.

about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!