How to forbid children for a React component with typescript?

Viewed 189

I have a React component for which I expect no children to be passed to it. Can I enforce it with typescript?

2 Answers

You can define the component's props like this:

type ComponentProps = {
  children?: undefined;
}
type MyComponentProps = {
  children?: never;
}

Valid cases:

  • <MyComponent />

Invalid cases:

  • <MyComponent>{undefined}</MyComponent>
  • <MyComponent>{'foobar'}</MyComponent>
  • <MyComponent>foobar</MyComponent>
  • <MyComponent><>foobar</></MyComponent>
  • <MyComponent><br /></MyComponent>
  • <MyComponent><b>foobar</b></MyComponent>
  • <MyComponent><Foo /></MyComponent>
Related