Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React children is not required in Typescript

I have this component:


interface TestI = {
  id: string;
}
const Test = ({children, id}: React.PropsWithChildren<TestI>) => {
  return <div id={id}>{children}</div>
}

Usage of the component:

<Test id={'hi'}></Test>

I expect to get a warning from TS that i did not use children for Test component.
Question: How to make children required?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

How to make children required?

Since there’s no any built-in type that has children as required prop (FC and PropsWithChildren has children as optional), you will have to add it by yourself.

interface TestI {
  id: string;
  children: React.ReactNode;
}

const Test = ({ children, id }: TestI) => {
  return <div id={id}>{children}</div>
}

<Test id="test"></Test> // Property 'children' is missing error
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading