Reduce IteratorIterable to exact type T

38 Views Asked by At

I need to write an hook that fetch the URL query parameters to return an object of strictly type T

export function useQueryParams<T>(): [
  T,
  ({ key, value }: { key: keyof T; value: string }) => void,
] {
  const [searchParams, setSearchParams] = useSearchParams()
  const entries = Array.from(searchParams.entries()).reduce(
    (acc, [key, value]) => {
      return { ...acc, [key]: value }
    },
    {} as T,
  )

  const setQueryParam = React.useCallback(
    ({ key, value }) => {
      searchParams.set(key, value)
      setSearchParams(searchParams)
    },
    [searchParams, setSearchParams],
  )

  return [entries, setQueryParam]
}

The problem of the above code is that it doesn't throw an error when the URL contains more parameters that are not part of T. The problem is the reduce function that return an object of type Partial<T> bypassing the check for the return type of the hook. How can I reduce correctly searchParams.entries() to get an object of type T containing exactly its properties?

EDIT: minimal reproducible example

0

There are 0 best solutions below