React TypeScript HoC - passing Component as the prop

0leg picture 0leg · Mar 14, 2018 · Viewed 13.7k times · Source

Following this tutorial: https://reacttraining.com/react-router/web/example/auth-workflow.

Trying to reproduce the code:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      fakeAuth.isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

In TypeScript:

import * as React from 'react';
import { Route, RouterProps } from 'react-router';

interface Props extends RouterProps {
  component: React.Component;
}

const PrivateRoute = ({ component: Component, ...rest }: Props) => {
  return (
    <Route
      {...rest}
      render={(props) => <Component {...props} />}
    />
  );
};

export default PrivateRoute;

But it would always fail. Tried different variations. The one I've posted the most recent one. Getting:

enter image description here

It seems to me that I have to pass Generic for the Component type, but I don't know how.

EDIT:

The closest solution so far:

interface Props extends RouteProps {
  component: () => any;
}

const PrivateRoute = ({ component: Component, ...rest }: Props) => {
  return (
    <Route
      {...rest}
      render={(props) => <Component {...props} />}
    />
  );
};

And then:

<PrivateRoute component={Foo} path="/foo" />

Answer

Titian Cernicova-Dragomir picture Titian Cernicova-Dragomir · Mar 14, 2018

You want to pass a component constructor, not a component instance:

import * as React from 'react';
import { Route, RouteProps } from 'react-router';

interface Props extends RouteProps {
    component: React.ComponentType;
}

const PrivateRoute = ({ component: Component, ...rest }: Props) => {
    return (
        <Route
            {...rest}
            render={(props) => <Component {...props} />}
        />
    );
};

export default PrivateRoute;

class Foo extends React.Component {

}
let r = <PrivateRoute component={Foo} path="/foo" />

Edit

A more complete solution should be generic and use RouteProps instead RouterProps:

import * as React from 'react';
import { Route, RouteProps } from 'react-router';

type Props<P> =  RouteProps & P & {
    component: React.ComponentType<P>;
}

const PrivateRoute = function <P>(p: Props<P>) {
    // We can't use destructuring syntax, because : "Rest types may only be created from object types", so we do it manually.
    let rest = omit(p, "component");
    let Component = p.component;
    return (
        <Route
            {...rest}
            render={(props: P) => <p.component {...props} />}
        />
    );
};

// Helpers
type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T];  
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>; 
function omit<T, TKey extends keyof T>(value:T, ... toRemove: TKey[]): Omit<T, TKey>{
    var result = Object.assign({}, value);
    for(let key of toRemove){
        delete result[key];
    }
    return result;
}


export default PrivateRoute;

class Foo extends React.Component<{ prop: number }>{

}
let r = <PrivateRoute component={Foo} path="/foo" prop={10} />