fix(nuxt): prevent getCachedData from shaping type of useAsyncData (#25946)

This commit is contained in:
Han 2024-04-09 01:38:40 +08:00 committed by GitHub
parent b6cd522402
commit 98a02744bd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 1 deletions

View File

@ -36,6 +36,8 @@ export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform
export type MultiWatchSources = (WatchSource<unknown> | object)[]
export type NoInfer<T> = [T][T extends any ? 0 : never]
export interface AsyncDataOptions<
ResT,
DataT = ResT,
@ -61,7 +63,7 @@ export interface AsyncDataOptions<
* A `null` or `undefined` return value will trigger a fetch.
* Default is `key => nuxt.isHydrating ? nuxt.payload.data[key] : nuxt.static.data[key]` which only caches data when payloadExtraction is enabled.
*/
getCachedData?: (key: string, nuxtApp: NuxtApp) => DataT
getCachedData?: (key: string, nuxtApp: NuxtApp) => NoInfer<DataT>
/**
* A function that can be used to alter handler function result after resolving.
* Do not use it along with the `pick` option.

View File

@ -512,6 +512,20 @@ describe('composables', () => {
expectTypeOf(notTypedData.value!.content).toEqualTypeOf<string[]>()
expectTypeOf(notTypedData.value!.untypedKey).toEqualTypeOf<any>()
})
it('correctly types returns when using with getCachedData', () => {
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: 1 }), {
getCachedData: key => useNuxtApp().payload.data[key],
}).data).toEqualTypeOf<Ref<{ foo: number } | null>>()
useAsyncData('test', () => Promise.resolve({ foo: 1 }), {
// @ts-expect-error cached data should return the same as value of fetcher
getCachedData: () => ({ bar: 2 }),
})
useAsyncData<{ foo: number }, unknown, { foo: number }>('test', () => Promise.resolve({ foo: 1 }), {
// @ts-expect-error cached data should return the same as asserted type of `useAsyncData`
getCachedData: () => ({ bar: 2 }),
})
})
})
describe('app config', () => {