I have a component that is used several times in a row with some identical properties and some unique properties:
interface InsideComponentProps {
repeatedThing: string;
uniqueThing: string;
}
const InsideComponent: React.SFC<InsideComponentProps> = ({ repeatedThing, uniqueThing }) => (
<div>{repeatedThing} - {uniqueThing}</div>
);
const Example = () => (
<div>
<InsideComponent repeatedThing="foo" uniqueThing="1" />
<InsideComponent repeatedThing="foo" uniqueThing="2" />
<InsideComponent repeatedThing="foo" uniqueThing="3" />
</div>
);
Duplicate properties repeatedThing
bother me, so I'm looking for a way to remove this redundancy. One thing I did in non TypeScript applications is to introduce a shell component that clones all the children, adding duplicate properties in the process:
interface OutsideComponentProps {
repeatedThing: string;
}
const OutsideComponent: React.SFC<OutsideComponentProps> = ({ repeatedThing, children }) => (
<div>
{React.Children.map(children, (c: React.ReactElement<any>) => (
React.cloneElement(c, { repeatedThing })
))}
</div>
);
const Example = () => (
<OutsideComponent repeatedThing="foo">
<InsideComponent uniqueThing="1" />
<InsideComponent uniqueThing="2" />
<InsideComponent uniqueThing="3" />
</OutsideComponent>
);
As a result, the JavaScript code has the behavior that I want, but the TypeScript compiler has errors, because I do not pass all the necessary properties when creating the instance InsideComponent
:
ERROR in [at-loader] ./src/index.tsx:27:26
TS2322: Type '{ uniqueThing: "1"; }' is not assignable to type 'IntrinsicAttributes & InsideComponentProps & { children?: ReactNode; }'.
Type '{ uniqueThing: "1"; }' is not assignable to type 'InsideComponentProps'.
Property 'repeatedThing' is missing in type '{ uniqueThing: "1"; }'.
, , , InsideComponent
repeatedThing
, , .
, InsideComponent
, ?
React 16.2.0 TypeScript 2.6.2.