简体   繁体   中英

How to forbid children for a React component with typescript?

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM