tatethurston / nextjs-routes

Type safe routing for Next.js
MIT License
553 stars 20 forks source link

do not hold query params and search params in the same object #157

Closed janwirth closed 1 year ago

janwirth commented 1 year ago

The type checking is less precise as it does not tell me if I have mistyped the path parameter because it could also be any query parameter.

tatethurston commented 1 year ago

@janwirth could you provide an example and explain your expected outcome for the example?

tatethurston commented 1 year ago

Search and query parameters in the same object is how next.js routing works, not a decision made by this library.

tatethurston commented 1 year ago

@janwirth feel free to reopen with more context

janwirth commented 1 year ago

So the exact problem was that I had an id query parameter which was actually called productId. I selected the id parameter and casted it to string.

const id = router.query.id as string

The generated types are:

  interface DynamicRoute<Pathname, Parameters> {
    pathname: Pathname;
    query: Parameters & Query;
    hash?: string | null | undefined;
  }

The software could be safer if the types were:

  interface DynamicRoute<Pathname, Parameters> {
    pathname: Pathname;
    pathParameters: Parameters;
    query: Query;
    hash?: string | null | undefined;
  }

I understand that nextJS might be merging the objects but we can provide both objects by using a custom useRouter hook and explicitly typing them differently.

tatethurston commented 1 year ago

@janwirth I'm hesitant to support an alternate API to Next's. If there is sufficient interest in this from other users I'll consider a runtime solution.

Future readers: if you are interested in this, add a 👍 to @janwirth's issue.

tran-simon commented 8 months ago

@tatethurston Maybe there should be a way to customize the Query interface?

I have some routes that I would like to strongly type the query params, but currently there is no way to do this. The type of any query param is string | string[] | undefined. Perhaps in the configuration, there could be a way to define some query param keys for a route?

The goal is that if for example I have a "user" query parameter, if I rename it to "userId" in some part of the code I would be warned to rename it everywhere it is used