Home > Back-end >  Why react router v6 useParams returns object with properties possibly 'undefined'?
Why react router v6 useParams returns object with properties possibly 'undefined'?

Time:11-17

Why react router v6 useParams returns object with properties possibly 'undefined'?

In my code below, my IDE indicates const slug: string | undefined.

const { slug } = useParams<"slug">();

It is because of the Params type definition:

/**
 * The parameters that were parsed from the URL path.
 */
export type Params<Key extends string = string> = {
  readonly [key in Key]: string | undefined;
};

But why is not Params defined like this (without the | undefined):

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

If a route with a parameter matches the URL then the parameter cannot be undefined. So, is there any case when useParams returns with an undefined param?

CodePudding user response:

Route params can be possibly undefined if the path has no defined parameters.

Example: "/path/to/page"

There are no route match params to access.

If you were to attempt to access a param

const { id } = useParams();

then id is of course, undefined.

  • Related