Saturday, February 3, 2018

How can I abstract passing repeated children properties while keeping types non-optional?

Leave a Comment

I have a component that gets used multiple times in succession 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> ); 

The duplicate repeatedThing properties bother me, so I'm seeking a way to remove that redundancy. One thing I've done in non-TypeScript applications is to introduce a wrapper component that clones all of the children, adding the repeated 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> ); 

The resulting JavaScript code has the behavior I want, but the TypeScript compiler has errors because I'm not passing all of the required properties when I instantiate 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"; }'. 

The only solution I've thought of is to mark InsideComponents repeatedThing property as optional, but that's not ideal because the value is required.

How can I preserve the strictness of making sure that InsideComponent does actually receive all of the props while reducing the duplication of the properties at the call site?

I'm using React 16.2.0 and TypeScript 2.6.2.

2 Answers

Answers 1

TypeScript checks to make sure that you assign all required properties to the React element. Since you assign the extra properties in the OutsideComponent the compiler can't really check that.

One option would be to specify children as a function that takes extra properties as a parameter and spread them to InsideComponent. The syntax is a bit more convoluted but it is more type safe:

interface OutsideComponentProps {     repeatedThing: string;     children: (outerProps: OutsideComponentProps) => React.ReactElement<any>; }  const OutsideComponent: React.SFC<OutsideComponentProps> = (o) => o.children(o);  const Example = () => (     <OutsideComponent repeatedThing="foo">{(o) =>          <div>             <InsideComponent uniqueThing="1" {...o} />             <InsideComponent uniqueThing="2" {...o} />             <InsideComponent uniqueThing="3" {...o} />         </div>     }</OutsideComponent> ); 

It seems that OutsideComponent is very abstract and thus reusable; is there any way to convert it into a very generic component that takes all of its props and provides them as the argument, without having to define an OutsideComponentProps for each case?

While you can use generic functions as components, you can't specify type parameters explicitly, they can only be inferred. This is a drawback, but ultimately it can be worked around.

function GenericOutsideComponent<T>(props: { children: (o: T) => React.ReactElement<any> } & Partial<T>, context?: any): React.ReactElement<any> {     return props.children(props as any); }  const Example = () => (     <GenericOutsideComponent repeatedThing="foo">{(o: InsideComponentProps) =>         <div>             <InsideComponent uniqueThing="1" {...o} />             <InsideComponent uniqueThing="2" {...o} />             <InsideComponent uniqueThing="3" {...o} />         </div>     }</GenericOutsideComponent> ); 

Similar to your original JavaScript solution, there is the risk that some required properties of InsideComponent are not specified as the properties of GenericOutsideComponent are Partial<T> (to allow only repeatedThing to be specified) and o is T because otherwise the compiler will consider repeatedThing is not specified and will require it on InsideComponent. If setting a dummy value on InsideComponent is not a problem, just change the signature of children to (o: Partial<T>) => React.ReactElement<any> but this is less then ideal.

Another option is to be explicit about which properties are on GenericOutsideComponent using a Pick:

function GenericOutsideComponent<T>(props: { children: (o: T) => React.ReactElement<any> } & T, context?: any): React.ReactElement<any> {     return props.children(props); }  const Example = () => (     <GenericOutsideComponent repeatedThing="foo">{(o: Pick<InsideComponentProps, "repeatedThing">) =>         <div>             <InsideComponent uniqueThing="1" {...o} />             <InsideComponent uniqueThing="2" {...o} />             <InsideComponent uniqueThing="3" {...o} />         </div>     }</GenericOutsideComponent> ); 

Answers 2

I'm new to TypeScript, but this may be an alternative:

// OutsideComponent.tsx import * as React from "react";  const OutsideComponent: React.SFC<{ children?: React.ReactNode, [rest: string]: any }> = (props) => {     const { children, ...rest } = props;      return (         <div>             {React.Children.map(children, ((child, i) =>                 React.cloneElement(child as React.ReactElement<any>, { key: i, ...rest }))             )}         </div>     ) };  type Sub<     O extends string,     D extends string     > = {[K in O]: (Record<D, never> & Record<string, K>)[K]}[O]  export type Omit<O, D extends keyof O> = Pick<O, Sub<keyof O, D>>  export default OutsideComponent; 

(Omit type taken from this answer)

Then

import OutsideComponent, { Omit } from './OutsideComponent';  const Example = (): React.ReactElement<any> => {     const PartialInsideComponent: React.SFC<Omit<InsideComponentProps, 'repeatedThing'>> = InsideComponent;      return (         <OutsideComponent repeatedThing="foo">             <PartialInsideComponent uniqueThing="1" />             <PartialInsideComponent uniqueThing="2" />             <PartialInsideComponent uniqueThing="3" />         </OutsideComponent>     ) }; 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment