What TypeScript type should I use to reference the match object in my props?

Nicolas Blanco picture Nicolas Blanco · Jan 7, 2018 · Viewed 42.7k times · Source

In my React containers/component, which type could I use to reference the match part included by React Router DOM?

interface Props {
  match: any // <= What could I use here instead of any?
}

export class ProductContainer extends React.Component<Props> {
  // ...
}

Answer

Nazar554 picture Nazar554 · Jan 7, 2018

You don't need to add it explicitly. You can use RouteComponentProps<P> from @types/react-router as a base interface of your props instead. P is type of your match params.

import { RouteComponentProps } from 'react-router';

// example route
<Route path="/products/:name" component={ProductContainer} />

interface MatchParams {
    name: string;
}

interface Props extends RouteComponentProps<MatchParams> {
}
// from typings
import * as H from "history";

export interface RouteComponentProps<P> {
  match: match<P>;
  location: H.Location;
  history: H.History;
  staticContext?: any;
}

export interface match<P> {
  params: P;
  isExact: boolean;
  path: string;
  url: string;
}