fix(type): improve type inference on asyncData option

This commit is contained in:
Xin Du (Clark) 2023-03-06 18:39:53 +00:00
parent 4f61e36c6f
commit e1c8015ff0
3 changed files with 62 additions and 56 deletions

View File

@ -28,13 +28,13 @@ type MultiWatchSources = (WatchSource<unknown> | object)[]
export interface AsyncDataOptions< export interface AsyncDataOptions<
DataT, DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>, TransformData = DataT,
PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> =KeysOf<TransformData>,
> { > {
server?: boolean server?: boolean
lazy?: boolean lazy?: boolean
default?: () => DataT | Ref<DataT> | null default?: () => TransformData | Ref<TransformData> | null
transform?: Transform transform?: _Transform<DataT, TransformData>,
pick?: PickKeys pick?: PickKeys
watch?: MultiWatchSources watch?: MultiWatchSources
immediate?: boolean immediate?: boolean
@ -64,33 +64,33 @@ const getDefault = () => null
export function useAsyncData< export function useAsyncData<
DataT, DataT,
DataE = Error, DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>, TransformData = DataT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>
> ( > (
handler: (ctx?: NuxtApp) => Promise<DataT>, handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys> options?: AsyncDataOptions<DataT, TransformData, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> ): AsyncData<PickFrom<TransformData, PickKeys>, DataE | null>
export function useAsyncData< export function useAsyncData<
DataT, DataT,
DataE = Error, DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>, TransformData = DataT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>
> ( > (
key: string, key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>, handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys> options?: AsyncDataOptions<DataT, TransformData, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> ): AsyncData<PickFrom<TransformData, PickKeys>, DataE | null>
export function useAsyncData< export function useAsyncData<
DataT, DataT,
DataE = Error, DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>, TransformData = DataT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> { > (...args: any[]): AsyncData<PickFrom<TransformData, PickKeys>, DataE | null> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) } if (typeof args[0] !== 'string') { args.unshift(autoKey) }
// eslint-disable-next-line prefer-const // eslint-disable-next-line prefer-const
let [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>] let [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, TransformData, PickKeys>]
// Validate arguments // Validate arguments
if (typeof key !== 'string') { if (typeof key !== 'string') {
@ -122,7 +122,7 @@ export function useAsyncData<
} }
} }
// TODO: Else, somehow check for conflicting keys with different defaults or fetcher // TODO: Else, somehow check for conflicting keys with different defaults or fetcher
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE> const asyncData = { ...nuxt._asyncData[key] } as AsyncData<TransformData, DataE>
asyncData.refresh = asyncData.execute = (opts = {}) => { asyncData.refresh = asyncData.execute = (opts = {}) => {
if (nuxt._asyncDataPromises[key]) { if (nuxt._asyncDataPromises[key]) {
@ -146,15 +146,16 @@ export function useAsyncData<
reject(err) reject(err)
} }
}) })
.then((result) => { .then((_result) => {
// If this request is cancelled, resolve to the latest request. // If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] } if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
let result = _result as unknown as TransformData
if (options.transform) { if (options.transform) {
result = options.transform(result) result = options.transform(_result)
} }
if (options.pick) { if (options.pick) {
result = pick(result as any, options.pick) as DataT result = pick(result as any, options.pick) as TransformData
} }
asyncData.data.value = result asyncData.data.value = result
asyncData.error.value = null asyncData.error.value = null
@ -239,36 +240,36 @@ export function useAsyncData<
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT, DataE> const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT, DataE>
Object.assign(asyncDataPromise, asyncData) Object.assign(asyncDataPromise, asyncData)
return asyncDataPromise as AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE> return asyncDataPromise as AsyncData<PickFrom<TransformData, PickKeys>, DataE>
} }
export function useLazyAsyncData< export function useLazyAsyncData<
DataT, DataT,
DataE = Error, DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>, TransformData = DataT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>
> ( > (
handler: (ctx?: NuxtApp) => Promise<DataT>, handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'> options?: Omit<AsyncDataOptions<DataT, TransformData, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> ): AsyncData<PickFrom<TransformData, PickKeys>, DataE | null>
export function useLazyAsyncData< export function useLazyAsyncData<
DataT, DataT,
DataE = Error, DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>, TransformData = DataT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>
> ( > (
key: string, key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>, handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'> options?: Omit<AsyncDataOptions<DataT, TransformData, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> ): AsyncData<PickFrom<TransformData, PickKeys>, DataE | null>
export function useLazyAsyncData< export function useLazyAsyncData<
DataT, DataT,
DataE = Error, DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>, TransformData = DataT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> { > (...args: any[]): AsyncData<PickFrom<TransformData, PickKeys>, DataE | null> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) } if (typeof args[0] !== 'string') { args.unshift(autoKey) }
const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>] const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, TransformData, PickKeys>]
// @ts-ignore // @ts-ignore
return useAsyncData(key, handler, { ...options, lazy: true }, null) return useAsyncData(key, handler, { ...options, lazy: true }, null)
} }

View File

@ -4,7 +4,7 @@ import type { Ref } from 'vue'
import { computed, unref, reactive } from 'vue' import { computed, unref, reactive } from 'vue'
import { hash } from 'ohash' import { hash } from 'ohash'
import { useRequestFetch } from './ssr' import { useRequestFetch } from './ssr'
import type { AsyncDataOptions, _Transform, KeyOfRes, AsyncData, PickFrom } from './asyncData' import type { AsyncDataOptions, _Transform, KeysOf, AsyncData, PickFrom } from './asyncData'
import { useAsyncData } from './asyncData' import { useAsyncData } from './asyncData'
export type FetchResult<ReqT extends NitroFetchRequest, M extends AvailableRouterMethod<ReqT>> = TypedInternalResponse<ReqT, unknown, M> export type FetchResult<ReqT extends NitroFetchRequest, M extends AvailableRouterMethod<ReqT>> = TypedInternalResponse<ReqT, unknown, M>
@ -17,11 +17,11 @@ type ComputedFetchOptions<R extends NitroFetchRequest, M extends AvailableRouter
export interface UseFetchOptions< export interface UseFetchOptions<
DataT, DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>, TransformData = DataT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>, PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>,
R extends NitroFetchRequest = string & {}, R extends NitroFetchRequest = string & {},
M extends AvailableRouterMethod<R> = AvailableRouterMethod<R> M extends AvailableRouterMethod<R> = AvailableRouterMethod<R>
> extends AsyncDataOptions<DataT, Transform, PickKeys>, ComputedFetchOptions<R, M> { > extends AsyncDataOptions<DataT, TransformData, PickKeys>, ComputedFetchOptions<R, M> {
key?: string key?: string
$fetch?: typeof globalThis.$fetch $fetch?: typeof globalThis.$fetch
} }
@ -32,23 +32,23 @@ export function useFetch<
ReqT extends NitroFetchRequest = NitroFetchRequest, ReqT extends NitroFetchRequest = NitroFetchRequest,
Method extends AvailableRouterMethod<ReqT> = 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT>, Method extends AvailableRouterMethod<ReqT> = 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT>,
_ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT, _ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT,
Transform extends (res: _ResT) => any = (res: _ResT) => _ResT, TransformData = _ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>
> ( > (
request: Ref<ReqT> | ReqT | (() => ReqT), request: Ref<ReqT> | ReqT | (() => ReqT),
opts?: UseFetchOptions<_ResT, Transform, PickKeys, ReqT, Method> opts?: UseFetchOptions<_ResT, TransformData, PickKeys, ReqT, Method>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null> ): AsyncData<PickFrom<TransformData, PickKeys>, ErrorT | null>
export function useFetch< export function useFetch<
ResT = void, ResT = void,
ErrorT = FetchError, ErrorT = FetchError,
ReqT extends NitroFetchRequest = NitroFetchRequest, ReqT extends NitroFetchRequest = NitroFetchRequest,
Method extends AvailableRouterMethod<ReqT> = 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT>, Method extends AvailableRouterMethod<ReqT> = 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT>,
_ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT, _ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT,
Transform extends (res: _ResT) => any = (res: _ResT) => _ResT, TransformData = _ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>
> ( > (
request: Ref<ReqT> | ReqT | (() => ReqT), request: Ref<ReqT> | ReqT | (() => ReqT),
arg1?: string | UseFetchOptions<_ResT, Transform, PickKeys, ReqT, Method>, arg1?: string | UseFetchOptions<_ResT, TransformData, PickKeys, ReqT, Method>,
arg2?: string arg2?: string
) { ) {
const [opts = {}, autoKey] = typeof arg1 === 'string' ? [{}, arg1] : [arg1, arg2] const [opts = {}, autoKey] = typeof arg1 === 'string' ? [{}, arg1] : [arg1, arg2]
@ -85,7 +85,7 @@ export function useFetch<
cache: typeof opts.cache === 'boolean' ? undefined : opts.cache cache: typeof opts.cache === 'boolean' ? undefined : opts.cache
}) })
const _asyncDataOptions: AsyncDataOptions<_ResT, Transform, PickKeys> = { const _asyncDataOptions: AsyncDataOptions<_ResT, TransformData, PickKeys> = {
server, server,
lazy, lazy,
default: defaultFn, default: defaultFn,
@ -101,7 +101,7 @@ export function useFetch<
let controller: AbortController let controller: AbortController
const asyncData = useAsyncData<_ResT, ErrorT, Transform, PickKeys>(key, () => { const asyncData = useAsyncData<_ResT, ErrorT, TransformData, PickKeys>(key, () => {
controller?.abort?.() controller?.abort?.()
controller = typeof AbortController !== 'undefined' ? new AbortController() : {} as AbortController controller = typeof AbortController !== 'undefined' ? new AbortController() : {} as AbortController
@ -124,28 +124,28 @@ export function useLazyFetch<
ReqT extends NitroFetchRequest = NitroFetchRequest, ReqT extends NitroFetchRequest = NitroFetchRequest,
Method extends AvailableRouterMethod<ReqT> = 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT>, Method extends AvailableRouterMethod<ReqT> = 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT>,
_ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT, _ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT,
Transform extends (res: _ResT) => any = (res: _ResT) => _ResT, TransformData = _ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>
> ( > (
request: Ref<ReqT> | ReqT | (() => ReqT), request: Ref<ReqT> | ReqT | (() => ReqT),
opts?: Omit<UseFetchOptions<_ResT, Transform, PickKeys, Method>, 'lazy'> opts?: Omit<UseFetchOptions<_ResT, TransformData, PickKeys, Method>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null> ): AsyncData<PickFrom<TransformData, PickKeys>, ErrorT | null>
export function useLazyFetch< export function useLazyFetch<
ResT = void, ResT = void,
ErrorT = FetchError, ErrorT = FetchError,
ReqT extends NitroFetchRequest = NitroFetchRequest, ReqT extends NitroFetchRequest = NitroFetchRequest,
Method extends AvailableRouterMethod<ReqT> = 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT>, Method extends AvailableRouterMethod<ReqT> = 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT>,
_ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT, _ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT,
Transform extends (res: _ResT) => any = (res: _ResT) => _ResT, TransformData = _ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform> PickKeys extends KeysOf<TransformData> = KeysOf<TransformData>
> ( > (
request: Ref<ReqT> | ReqT | (() => ReqT), request: Ref<ReqT> | ReqT | (() => ReqT),
arg1?: string | Omit<UseFetchOptions<_ResT, Transform, PickKeys, Method>, 'lazy'>, arg1?: string | Omit<UseFetchOptions<_ResT, TransformData, PickKeys, Method>, 'lazy'>,
arg2?: string arg2?: string
) { ) {
const [opts, autoKey] = typeof arg1 === 'string' ? [{}, arg1] : [arg1, arg2] const [opts, autoKey] = typeof arg1 === 'string' ? [{}, arg1] : [arg1, arg2]
return useFetch<ResT, ErrorT, ReqT, _ResT, Transform, PickKeys>(request, { return useFetch<ResT, ErrorT, ReqT, _ResT, PickKeys>(request, {
...opts, ...opts,
lazy: true lazy: true
}, },

View File

@ -199,9 +199,7 @@ describe('composables', () => {
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number | null>>() expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number | null>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => 500 }).data).toEqualTypeOf<Ref<number | null>>() expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => 500 }).data).toEqualTypeOf<Ref<number | null>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number | null>>() expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number | null>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => 500 }).data).toEqualTypeOf<Ref<number | null>>() expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => 500 }).data).toEqualTypeOf<Ref<number | null>>()
expectTypeOf(useFetch('/test', { default: () => ref(500) }).data).toEqualTypeOf<Ref<number | null>>() expectTypeOf(useFetch('/test', { default: () => ref(500) }).data).toEqualTypeOf<Ref<number | null>>()
@ -235,6 +233,13 @@ describe('composables', () => {
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() }))) .toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo })) expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo })) .toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
// Default values: #14437
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: { bar: 500 } }), { default: () => ({ bar: 500 }), transform: v => v.foo }).data).toEqualTypeOf<Ref<{bar: number} | null>>()
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: { bar: 500 } }), { default: () => ({ bar: 500 }), transform: v => v.foo }))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: { bar: 500 } }), { default: () => ({ bar: 500 }), transform: v => v.foo }))
expectTypeOf(useFetch('/api/hey', { default: () => 'bar', transform: v => v.foo }).data).toEqualTypeOf<Ref<string | null>>()
expectTypeOf(useLazyFetch('/api/hey', { default: () => 'bar', transform: v => v.foo }).data).toEqualTypeOf<Ref<string | null>>()
}) })
}) })