N
Nuxtβ€’3mo ago
Flo

Preserve types in custom useFetch composable?

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 });
}
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 });
}
8 Replies
Fabian B.
Fabian B.β€’3mo ago
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> {
// ...
}
export async function useBetterFetch<T = any>(
url: Parameters<typeof $fetch>[0],
options: Parameters<typeof $fetch>[1] = {}
): Promise<T> {
// ...
}
No description
Flo
Floβ€’3mo ago
Mhm... It's more about the result of that $fetch (Just noticed I forgot the screenshots)
Flo
Floβ€’3mo ago
No description
No description
Flo
Floβ€’3mo ago
I think I got it:
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 });
};
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)
Fabian B.
Fabian B.β€’3mo ago
Just saw your messages, yeah that would have been the way I would have gone too
Flo
Floβ€’3mo ago
I kept trying, with no success. Something is always off πŸ˜„ sorry! That was accidental πŸ˜“ @Fabian B.
export const useInternalApi = () =>
$fetch.create({
headers: useRequestHeaders(["cookie"]),
});
export const useInternalApi = () =>
$fetch.create({
headers: useRequestHeaders(["cookie"]),
});
- sometimes it can be simple.
Fabian B.
Fabian B.β€’3mo ago
πŸ˜„ True, though $fetch.create does not have the same methods such as $fetch, but if it works for your case than it's perfect!
Flo
Floβ€’3mo ago
At least it managed to keep the type information, of the fetched routes - which makes me very happy πŸ˜„
Want results from more Discord servers?
Add your server
More Posts