In React with TypeScript, I’m looking for a way to type children
on a component so that it can accept 1 or 2 ReactElement
, and I was wondering if there is a way to type something as, for example, ReactElement | nothing
, for the 2nd element, where “nothing” is the equivalent of it not being declared in the JSX at all (so, different from undefined
or null
).
I know you can use ReactElement | [ReactElement, ReactElement]
to say “either 1 or 2 ReactElement”, but that gets annoying the more elements you add.
In the code below, ExampleUseOne
is fine but ExampleUseTwo
isn’t, which makes sense.
I’m wondering if there’s a type I can add to the 2nd children that would make both examples work.
import React, { ReactElement } from "react";
type Props = {
children: [ReactElement, ReactElement | null];
}
const Component = ({ children }: Props) => {
return (
<div>{children}</div>
);
};
const Part = () => {
return <div>Part</div>;
};
const ExampleUseOne = ({ hasTwoParts }: { hasTwoParts?: boolean }) => {
return (
<Component>
<Part />
{/* ???? returns `ReactElement` or `null` so TS is ok with it */}
{hasTwoParts ? <Part /> : null}
</Component>
)
}
const ExampleUseTwo = ({ hasTwoParts }: { hasTwoParts?: boolean }) => {
return (
<Component>
<Part />
{/* nothing declared here, so TS is complaining that it doesn't match the type signature */}
</Component>
)
}
Here’s the TS Playground link for the above.
Finally, I know that ReactElement | [ReactElement, ReactElement | null]
works in this case, but it seems silly to have to repeat the 1st element since it doesn’t change. So, for the 2nd element, is there a type, call it T
, I can add that matches the element not being defined in the JSX, so that I can use for the whole children
type this: [ReactElement, ReactElement | null | T]
?
I tried using the several special types I know: never
, unknown
, void
, undefined
, to no avail.
bvaugenot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.