dwjohnston
dwjohnston

Reputation: 11781

Typescript interface for a Functional Component that requires children

I typically define my functional react components with the following pattern:

interface Props {
    title: string; //for example
}

export const MyComponent : React.FunctionComponent<Props> = (props) => {
    const {
        title, 
        children //This is implied as allowed by the FunctionalCompoment interface I believe

    } = props; 

     return <div>{title}{children}</div> 
}

I have a component that must have children, as a lot of react components do.

How do I enforce this?

On a related note, is it possible to enforce that the children must of a certain kind of React component?

Upvotes: 0

Views: 170

Answers (1)

Avin Kavish
Avin Kavish

Reputation: 8937

This is the built in way but children are optional in this type.

export const MyComponent : React.FunctionComponent<React.PropsWithChildren<Props>> = (props) => {
  const {
    title,
    children //This is implied as allowed by the FunctionalCompoment interface I believe

  } = props;

  return <div>{title}{children}</div>
}

I would suggest creating your own type or interface

type MustHaveChildren<T> = T & { children: ReactNode }

or

interface MustHaveChildren {
 children: ReactNode
}

interface T extends MustHaveChildren {
 .... // your types
}

Usage:

Type

export const MyComponent : React.FunctionComponent<MustHaveChildren<Props>> = 
  (props) => (...)

Interface

export const MyComponent : React.FunctionComponent<Props> = 
  (props) => (...)

Upvotes: 2

Related Questions