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

126
Views
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
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!