Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
Typescript & React. Ensure there's one child of specific type in children on compile time

I wonder if is it possible, on Typescript side, to make sure that a react Component receives one child of a x type, independ on whatever else it receives.

Here's a use case:

In a "System Design" like aproach, i have a Section Component, and a Title Component as well. I want to make sure that all Sections receive at least one Title as child (One h1, or at least one h2 more specifically), and still receives any other children (or not, whatevs).

So those would be valid:

<Section ...>
    <Title level={1}>Title</Title>
    ...
</Section>

<Section ...>
    <Title level={1}>Title</Title>
    <Title level={2}>Sub-title</Title>
    ...
</Section>

<Section ...>
    <Title level={2}>Title</Title>
    <Title level={2}>Sub-title</Title>
    <Title level={2}>yada-yada</Title>
    ...
</Section>

Those would not:

<Section ...>
    <p>some text</p>
    ...
</Section>

<Section ...>
    <Title level={1}>Title</Title>
    <Title level={1}>Other Title</Title>
    ...
</Section>

<Section ...>
    <Title level={3}>Title</Title>
    ...
</Section>

For now, inside component, i'm looping through children, and if no matching Title is found, an Error is thrown:

if (!sectionTitle) throw new Error(...)

So, a future dev using it wrong, gets warned by the browser.

But i would really like to do this check on Typescript, so the error show up on build, and not only after opening the page.

There is a way to do that?

Here's a minimal and clear working example: https://codesandbox.io/s/romantic-surf-tpyojt?file=/src/components/Section.tsx

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda