Source:  Twitter logo

I get a typeScript error after upgrading to version 4 Used in useParams () from react-router-dom

"typescript": "^4.0.2"

import { useParams } from 'react-router-dom';

const { sumParams } = useParams();

Property 'sumParams' does not exist on type '{}'. 

The project worked great and only after the upgrade does it throw an error

useParams is generic. You need to tell typescript which params you are using by specifying the value of the generic

There are several ways to solve this

This is my favorite way

const { sumParams } = useParams<{ sumParams: string }>();

But there are a few more ways (:


interface ParamTypes {
  sumParams: string;

Then in your Component

const { sumParams } = useParams<ParamTypes>();


add any type without interface

const { sumParams } : any = useParams();

Note: that this way you will not be able to set it as a string


More option for keemor:

const { sumParams } = useParams() as { 
  sumParams: string;
172 users liked answer #0dislike answer #0172
Yoel profile pic

Another option is:

const { sumParams } = useParams() as { 
  sumParams: string;
12 users liked answer #1dislike answer #112
keemor profile pic

To make it function as before, just add ":any"

const { sumParams } : any = useParams();
5 users liked answer #2dislike answer #25
osoblanco profile pic

For newer versions of the router, generic is changed from object to union of strings.

const { param1, param2 } = useParams<'param1' | 'param2'>();

Current useParams type in the react-router types looks like this:

export declare function useParams<Key extends string = string>(): Readonly<Params<Key>>;
1 users liked answer #3dislike answer #31
Mario Petrovic profile pic
Mario Petrovic
type ParamTypes {
  sumParams: string;

const { sumParams } = useParams<ParamTypes>()

this would be the clean approach to take


const { sumParams } = useParams<{[key: string] : string}>()

with this approach, you can get as many as param you want without declaring individually

0 users liked answer #4dislike answer #40
Shailesh Parmar profile pic
Shailesh Parmar

You can also access the params from useRouteMatch if you already have it imported in your file

const curRoute = useRouteMatch();
// @ts-ignore
let sumParams  = curRoute.params.sumParams
-1 users liked answer #5dislike answer #5-1
Caleb C. Adainoo profile pic
Caleb C. Adainoo

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).