TanStackT
TanStack2y ago
5 replies
rubber-blue

Can we have different types for search params input and output?

By search params input I mean:
<Link to="/" search={{page: 1}} /> // <-- input is the arguments we pass to the `search` prop


and by output I mean:
// route

const IndexRoute() => {
  const {page, size} = Route.useSearch() // output is the return value of the `useSearch` hook
}


I have many routes that have page and size search params. I don't want to specify these values for every page in every link. That is why I use default values with zod. However, each page can have different default values for size, and I want to specify this default only once inside each route's search params' schema. Some pages can have more search params and here I face problems:

For example /users page can have a 3rd param: sort. And I have a link:
<Link to="/users" search={{sort: '-name'}} />

I get a typescript error that requires me to add page and size . But I don't want to, I want them to be empty here and the validateSearch and zod to apply the default values automatically. If I change the return type of validateSearch to make the search params optional, then I get optional types in the output:

// route
const {page, size} = Route.useSearch() // page and size are of type `number | undefined`

But they have a fallback, and their types should be just number.

Could you please help me, how can I make sure that I can omit optional properties which have default values from the search prop and get the non-optional variables from the useSearch hook? As far as I understood, both of the types are controlled by the return type of the validateSearch
Was this page helpful?