#Preserve types in custom useFetch composable?

12 messages · Page 1 of 1 (latest)

grizzled cypress
#

Probably just missing typescript knowledge... my custom fetch composable doesn't give me the type hints for the requested route while useFetch does that.

export async function useBetterFetch<T = any>(
  url: string,
  options: Parameters<typeof $fetch>[1] = {}
): Promise<T> {
  const requestHeaders = useRequestHeaders(["cookie"]);

  const headers = { ...options.headers, ...requestHeaders };

  return await $fetch<T>(url, { ...options, headers });
}```
glossy isle
#

Hi there, you can assign Parameters[0] to be your url type, which gives you the hints:

export async function useBetterFetch<T = any>(
  url: Parameters<typeof $fetch>[0],
  options: Parameters<typeof $fetch>[1] = {}
): Promise<T> {
  // ...
}
grizzled cypress
#

Mhm... It's more about the result of that $fetch

#

(Just noticed I forgot the screenshots)

grizzled cypress
#

I think I got it: ```ts
export const useAnotherFetch: typeof useFetch = (
url: Parameters<typeof useFetch>[0],
options: Parameters<typeof useFetch>[1]
) => {
const requestHeaders = useRequestHeaders(["cookie"]);
const headers = { ...options?.headers, ...requestHeaders };

return useFetch(url, { ...options, headers });
};```

#

(well, partially. Signature doesn't seem to be fully compatible)

glossy isle
#

Just saw your messages, yeah that would have been the way I would have gone too

grizzled cypress
#

I kept trying, with no success. Something is always off 😄

#

sorry! That was accidental 😓

grizzled cypress
#

@glossy isle ```ts
export const useInternalApi = () =>
$fetch.create({
headers: useRequestHeaders(["cookie"]),
});

glossy isle