How to specify the result type of useParams with react router v6?

Viewed 971

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).

1 Answers

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;
Related