N
Nuxt2y ago
Markeem

Wrapping $fetch in composable with default options while retaining type safety

I managed to get autocomplete for the routes, but the return type is unknown. How can I get the return type working ? Example:
import type { NitroFetchRequest } from 'nitropack'

export function useFetchWithDefaultOptions(url: NitroFetchRequest) {
return $fetch(url, {
headers: {
defaultHeader: 'value',
},
})
}
import type { NitroFetchRequest } from 'nitropack'

export function useFetchWithDefaultOptions(url: NitroFetchRequest) {
return $fetch(url, {
headers: {
defaultHeader: 'value',
},
})
}
1 Reply
Markeem
MarkeemOP2y ago
I found this somewhere in the nitro sourcecode:
import { $fetch } from "ofetch";
import { $Fetch, NitroFetchRequest } from "../types";
if (!globalThis.$fetch) {
globalThis.$fetch = $fetch as $Fetch<unknown, NitroFetchRequest>;
}
import { $fetch } from "ofetch";
import { $Fetch, NitroFetchRequest } from "../types";
if (!globalThis.$fetch) {
globalThis.$fetch = $fetch as $Fetch<unknown, NitroFetchRequest>;
}
So I changed my composable to:
import type { NitroFetchRequest } from 'nitropack'

export function useFetchWithDefaultOptions<T extends NitroFetchRequest>(url: T) {
return $fetch<unknown, T>(url, {
headers: {
defaultHeader: 'value',
},
})
}
import type { NitroFetchRequest } from 'nitropack'

export function useFetchWithDefaultOptions<T extends NitroFetchRequest>(url: T) {
return $fetch<unknown, T>(url, {
headers: {
defaultHeader: 'value',
},
})
}
And it seems to work on first look. Maybe someone from the team can confirm if this is valid ?
Want results from more Discord servers?
Add your server