Chiawen
Chiawen

Reputation: 11809

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?

Upvotes: 3

Views: 456

Answers (2)

igor
igor

Reputation: 5475

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>

Upvotes: 1

Abe
Abe

Reputation: 5508

You can define the component's props like this:

type ComponentProps = {
  children?: undefined;
}

Upvotes: 1

Related Questions