Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 852
Asking Avatar asked Jan 23 '26 04:01

Asking


2 Answers

You should declare that your component requires children explicitly:

const TestComponent = (props: {children: React.ReactNode, id: string}) => {
    return (
        <div id={props.id}>{props.children}</div>
    );
}

See this example in TS playground.

Also, children are optional in React.PropsWithChildren type - that's why there is no error (link to types). And I wouldn't use this generic anyway, since it only adds children prop to the passed type and usage of such generics is discouraged by community.

like image 60
showmeyourhits Avatar answered Jan 25 '26 21:01

showmeyourhits


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
like image 42
kind user Avatar answered Jan 25 '26 20:01

kind user



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!