1

I am trying out Typescript with react (never worked before). I Solved a problem but I am not sure if this is the proper way to do it.

So my route in react looks like this

<Route exact path='/show/:id' component={ShowIssues} />

And my component solved is looking like this

import React from "react";
import { RouteProps } from "react-router-dom";

interface RouteInfo extends RouteProps {
  params: {
    id: string;
  };
}

const ShowIssues = ({ match }: { match: RouteInfo }) => {
  const { params }: { params: { id: string } } = match;
  const { id }: { id: string } = params;

  return <div>time to show the issue {id}</div>;
};

export default ShowIssues;

Is correct solved in the props this match? Surprisingly I've not found almost anything regarding function components ( and hooks are coming, so I guess makes sense to raise this doubt).

My other doubt goes for const { params }: { params: { id: string } } = match; is there a way I can reuse the RouteInfo so I don't have to type it twice?

Thanks!

1 Answer 1

4

const { params }: { params: { id: string } } and const { id }: { id: string } types are redundant because they will be inferred if match was typed properly.

Route props are an object with specific type that has match property, RouteComponentProps. It accepts match.params type as generic parameter.

It should be:

interface RouteInfo extends RouteProps {
    id: string;
}

const ShowIssues = ({ match }: RouteComponentProps<RouteInfo>) => {
  const { params } = match;
  const { id } = params;

  return <div>time to show the issue {id}</div>;
};
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect, that's exactly what I was looking for. I wasn't seeing it properly to type it every time neither.
Just to double check and make sure all good: with RouteComponentProps is already pointing into params, so I just have to specify the id: string in my type? with the wrapper of params was failing and without it looks good
That's correct. See github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/… on how it works. I updated the answer for clarity.
Aren't RouteProps properties for <Route />? Extending them seems redundant here and actually raised weird TS errors for me. This works well enough: interface RouteInfo { ... .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.