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

110
Views
Reaccionar componente de flujo de control con Typescript

Tengo un componente de flujo de control con React que

  • da a sus children cuando la condición es true ,
  • se vuelve null o una alternativa si la condición es false

El componente

 interface Props { when: boolean fallback?: () => JSX.Element children: Children } export const Show = ({ when, fallback, children }: Props) => { if (!when) return <>{fallback?.() || null}</> return <>{children}</> }

Sin el componente

si no uso este componente y uso un operador binario simple, TypeScript funciona muy bien:

 interface Props { value: {nested: string} | null } const SomeComponent =({value}:Props)=>( <div> {value && ( <div> {value.nested} value is inferred the type "{nested: string}" </div> )} </div>

con el componente

Si uso el componente de flujo de control, el tipo no se infiere y mecanografiado da un error:

 interface Props { value: {nested: string} | null } const SomeComponent =({value}:Props)=>( <div> <Show when={!!value}> <div> {value?.nested} typeof value remains "{nested: string} | null", therefore I need some conditional chaining </div> </Show> </div>

¿Alguna idea sobre cómo hacer que la inferencia de tipos funcione?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No puede hacerlo de esta manera, porque el código dentro de <Show></Show> en realidad se ejecuta antes de que Show tenga la oportunidad de evitar que se represente el div . Piense en lo que sucede cuando JSX se transpila a javascript:

 React.createElement( Show, {when: !!value}, React.createElement( 'div', {}, `${value?.nested} typeof value remains "{nested: string} | null", therefore I need some conditional chaining` ) )

¿Ves el problema? Si lo reescribimos un poco:

 const textContent = `${value?.nested} typeof value remains "{nested: string} | null", therefore I need some conditional chaining` React.createElement( Show, {when: !!value}, React.createElement( 'div', {}, textContent ) )

Estos fragmentos son exactamente iguales, y en ambos value?.nested se evalúa antes de que Show incluso se procese. No puedo recomendarle ninguna buena solución aquí, tal vez algo como esto:

 interface Props<T> { value: T fallback?: () => JSX.Element children: (value: T) => ReactNode } export const CheckExists = <T extends any>({ value, fallback, children }: Props<T>) => { if (!value) return fallback ? fallback() : null return <>{children(value)}</> } <CheckExists value={value}> {existingValue => ( <div>{existingValue.nested}</div> )} </CheckExists>

Pero esta es una interfaz diferente y puede no ser adecuada para usted

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!