From 7b9f4b8dd96058a49e3e7042ea326e86b643b22a Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 2 Dec 2024 15:40:44 +0000 Subject: [PATCH] fix(nuxt): correct return type of `useRequestFetch` (#30117) --- packages/nuxt/src/app/composables/ssr.ts | 5 +++-- test/fixtures/basic-types/types.ts | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/nuxt/src/app/composables/ssr.ts b/packages/nuxt/src/app/composables/ssr.ts index 59db9bd327..41091a6f47 100644 --- a/packages/nuxt/src/app/composables/ssr.ts +++ b/packages/nuxt/src/app/composables/ssr.ts @@ -2,6 +2,7 @@ import type { H3Event } from 'h3' import { setResponseStatus as _setResponseStatus, appendHeader, getRequestHeader, getRequestHeaders, getResponseHeader, removeResponseHeader, setResponseHeader } from 'h3' import { computed, getCurrentInstance, ref } from 'vue' import { useServerHead } from '@unhead/vue' +import type { H3Event$Fetch } from 'nitro/types' import type { NuxtApp } from '../nuxt' import { useNuxtApp } from '../nuxt' @@ -39,11 +40,11 @@ export function useRequestHeader (header: string) { } /** @since 3.2.0 */ -export function useRequestFetch (): typeof global.$fetch { +export function useRequestFetch (): H3Event$Fetch | typeof global.$fetch { if (import.meta.client) { return globalThis.$fetch } - return useRequestEvent()?.$fetch as typeof globalThis.$fetch || globalThis.$fetch + return useRequestEvent()?.$fetch || globalThis.$fetch } /** @since 3.0.0 */ diff --git a/test/fixtures/basic-types/types.ts b/test/fixtures/basic-types/types.ts index 5b9f7b9883..7e022eaa0e 100644 --- a/test/fixtures/basic-types/types.ts +++ b/test/fixtures/basic-types/types.ts @@ -34,6 +34,23 @@ describe('API routes', () => { expectTypeOf($fetch('/test')).toEqualTypeOf>() }) + it('works with useRequestFetch', () => { + const $fetch = useRequestFetch() + expectTypeOf($fetch('/api/hello')).toEqualTypeOf>() + // registered in extends + expectTypeOf($fetch('/api/foo')).toEqualTypeOf>() + // registered in module + expectTypeOf($fetch('/auto-registered-module')).toEqualTypeOf>() + expectTypeOf($fetch('/api/hey')).toEqualTypeOf>() + expectTypeOf($fetch('/api/hey', { method: 'get' })).toEqualTypeOf>() + expectTypeOf($fetch('/api/hey', { method: 'post' })).toEqualTypeOf>() + // @ts-expect-error not a valid method + expectTypeOf($fetch('/api/hey', { method: 'patch ' })).toEqualTypeOf>() + expectTypeOf($fetch('/api/union')).toEqualTypeOf>() + expectTypeOf($fetch('/api/other')).toEqualTypeOf>() + expectTypeOf($fetch('/test')).toEqualTypeOf>() + }) + it('works with useAsyncData', () => { expectTypeOf(useAsyncData('api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf>() expectTypeOf(useAsyncData('api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf>()