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?

>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

Leave a Reply