Home > database >  React children is not required in Typescript
React children is not required in Typescript

Time:10-27

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related