7

With react router v5, to specify the result type of useParams, I used:

const { param1, param2 } = useParams<{ param1: string, param2: string }>();

How can I do that with react router v6?

I cannot figure out how to type more than 1 parameter (e.g.: useParams<"param1">()) and I cannot figure out how to type the param as string and not string | undefined (see question).

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
soliz
  • 735
  • 1
  • 7
  • 17

2 Answers2

4

I was searching for the same thing, and after looking into typings of useParams I figured out that you need to pass keys of params as strings like:

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

If you want multiple params just use typescript's | like in the example below.

type Params = 'a' | 'b' | 'c';
// ...
const params = useParams<Params>();

The returned object's values will always have type of string | undefined because of react router typings.

export declare type Params<Key extends string = string> = {
    readonly [key in Key]: string | undefined;
};

But at the end of the day you can always use typescript's as

interface Params {
    a: string;
}

const params = useParams<keyof Params>() as Params;
Seba
  • 95
  • 1
  • 12
0

In the current version (6.14.1), you can use types instead of interfaces.

type Params {
    a: string;
}

const params = useParams<Params>();
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 12 '23 at 18:57