Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda