0

I have the following component using react-router-dom:

<Route path='/restaurants/:id' render={props => (
  <Restaurant {...props} user={user} />
)} />

Now, in my Restaurant.tsx code, I can't seem to figure out what should be the proper type for props below:

const Restaurant = (props: RouteComponentProps<{id: string}>) => {
  const a = props.match.params.id;
  const b = props.user;

  ...
}

With the type RouteComponentProps<{id: string}>, a is assigned a value without error. However, that's not the case for b:

Property 'user' does not exist on type 'RouteComponentProps<{ id: string; }, StaticContext, unknown>'

What should be the type of props so that I can get the extra attribute user={user} that's passed to the component using props.user without any type errors?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Loqz
  • 373
  • 4
  • 16

1 Answers1

1

Declare interface for props of Restaurant component and extends RouteComponentProps interface.

import React from 'react';
import { Route, RouteComponentProps } from 'react-router-dom';

interface RestaurantProps extends RouteComponentProps<{ id: string }> {
  user: any;
}
const Restaurant = (props: RestaurantProps) => {
  const a = props.match.params.id;
  const b = props.user;
  return <div>Restaurant</div>
}

const App = () => {
  const user = {};
  return (
    <Route
      path="/restaurants/:id"
      render={(props) => <Restaurant {...props} user={user} />}
    />
  );
};

TypeScript Playground

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Awesome, it works! Thanks! Just wondering if there's a way to do this without using interfaces? Because initially, I thought RouteComponentProps has built-in features for those extra attributes. – Loqz Sep 25 '21 at 03:50
  • No it doesn't, you are supposed to do it using type intersections – Alex Chashin Sep 25 '21 at 13:31