react-docgen-typescript icon indicating copy to clipboard operation
react-docgen-typescript copied to clipboard

'required' attribute set to false when intersection used

Open leepowelldev opened this issue 4 years ago • 4 comments

Sorry, this is a bit vague ... but I have the following component:

import { HTMLAttributes, ReactNode } from 'react';

type Props = {
  children: ReactNode;
  title: string;
};

const Test = ({ children, title, ...rest }: Props) => (
  <div {...rest}>
    <h2>{title}</h2>
    {children}
  </div>
);

Test.displayName = 'Test';

export { Test };

In this instance, both children and title are correctly marked as required. However, when I use an intersection type like so to allow additional, valid html props ...

import { HTMLAttributes, ReactNode } from 'react';

type Props = {
  children: ReactNode;
  title: string;
} & HTMLAttributes<HTMLDivElement>;

const Test = ({ children, title, ...rest }: Props) => (
  <div {...rest}>
    <h2>{title}</h2>
    {children}
  </div>
);

Test.displayName = 'Test';

export { Test };

... then for some reason both children and title are no longer marked as required. Am I doing something wrong to cause this?

leepowelldev avatar Apr 02 '21 10:04 leepowelldev

I have found a workaround:

interface Props extends HTMLAttributes<HTMLDivElement> {
  children: ReactNode;
  title: string;
}

leepowelldev avatar Apr 02 '21 10:04 leepowelldev

Another oddity, when children is set to something other than ReactNode and a intersection is used I seem to get an intersection type returned:

type Props = {
  children: string;
  title: string;
} & HTMLAttributes<HTMLDivElement>

In this instance I would get children as type string & ReactNode

Screenshot 2021-04-02 at 12 15 56

However, using extends works as expected:

Screenshot 2021-04-02 at 12 17 56

leepowelldev avatar Apr 02 '21 11:04 leepowelldev

There was no activity for a long time. Closing this issue as obsolete. In case it is still valid, please, open a new one.

github-actions[bot] avatar Oct 09 '21 10:10 github-actions[bot]

I could be wrong but I believe the reason for this is that HTMLAttributes already provides an optional title prop, which is overwriting yours. HTMLAttributes is also extending DOMAttributes internally which provides an optional children prop that is again, overwriting yours.

The fix would be in the order of your props:

type Props = HTMLAttributes<HTMLDivElement> & {
  children: ReactNode;
  title: string;
};

Kosai106 avatar Mar 30 '22 09:03 Kosai106

There was no activity for a long time. The issue will be closed soon.

github-actions[bot] avatar Mar 30 '23 10:03 github-actions[bot]

Closing this issue as obsolete.

github-actions[bot] avatar Apr 06 '23 10:04 github-actions[bot]