Skip to content

Instantly share code, notes, and snippets.

@davidparys
Created March 1, 2025 18:18
Show Gist options
  • Save davidparys/d06fab8d580e301342c124c9191647ea to your computer and use it in GitHub Desktop.
Save davidparys/d06fab8d580e301342c124c9191647ea to your computer and use it in GitHub Desktop.
Typed fetch for api routes in nuxt
// composables/useTypedFetch.ts
import type { UseFetchOptions } from 'nuxt/app'
import type { InternalApi } from 'nitropack'
import type { ApiRoutes, ApiResponse } from './apiResponse'
export const useTypedFetch = <T extends ApiRoutes, M extends keyof InternalApi[T]>(
route: T,
method: M,
opts?: Omit<UseFetchOptions<ApiResponse<T, M>>, 'method'>
) => {
return useFetch(route, {
...opts,
method: method as any, // Type assertion needed due to Nuxt's type constraints
transform: (response) => response as ApiResponse<T, M>
})
}
<script setup lang="ts">
const { data, status, error } = useTypedFetch('/api/properties/:id', 'default')
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment