React.PropsWithChildren with no props other than `children`?

I have a component with no props other than children, i.e.:

function Foo({ children }: React.PropsWithChildren<>) {}

React.PropsWithChildren requires an argument. If I do React.PropsWithChildren<{}>, Eslint produces Don't use `{}` as a type. `{}` actually means "any non-nullish value"..

I’m using this for the empty object type:

type EmptyObj = { [k: string]: never };

However, React.PropsWithChildren<EmptyObj> causes:

Type '{ children: Element; }' is not assignable to type 'EmptyObj'.
  Property 'children' is incompatible with index signature.
    Type 'Element' is not assignable to type 'never'.

What should I pass to React.PropsWithChildren?

Edit:

I know I can just do:

function Foo({ children }: { children?: React.ReactNode }) {}

However, I’m using React.PropsWithChildren throughout the codebase, so I’d prefer to keep it consistent.

2 thoughts on “React.PropsWithChildren with no props other than `children`?”

  1. Looking at how React.FC<> implemented you can try:

    interface WrapperProps<> {}
    
    function App(props: React.PropsWithChildren<WrapperProps>) {
      return <div>{props.children}...</div>;
    }
    
    Reply
  2. You can just leverage the FC type as follows:

    const Foo: FC = ({ children }) => {
        return <div>{children}</div>;
    };
    

    If you really want to stick to PropsWithChildren, then use PropsWithChildren<unknown> instead of PropsWithChildren<{}>. The warning you get comes from typescript-eslint and can be turned off for those cases as another option.

    Reply

Leave a Comment