'required' attribute set to false when intersection used
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?
I have found a workaround:
interface Props extends HTMLAttributes<HTMLDivElement> {
children: ReactNode;
title: string;
}
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
However, using extends works as expected:
There was no activity for a long time. Closing this issue as obsolete. In case it is still valid, please, open a new one.
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;
};
There was no activity for a long time. The issue will be closed soon.
Closing this issue as obsolete.