diff --git a/subscription/index.ts b/subscription/index.ts index bc8f8e21c..4323c78c1 100644 --- a/subscription/index.ts +++ b/subscription/index.ts @@ -8,8 +8,12 @@ import { createCacheHelper } from 'swr/_internal' -export type SWRSubscription = ( - key: Key, +export type SWRSubscription< + Data = any, + Error = any, + SWRKey extends Key = Key +> = ( + key: SWRKey, { next }: { next: (err?: Error | null, data?: Data) => void } ) => () => void @@ -18,11 +22,13 @@ export type SWRSubscriptionResponse = { error?: Error } -export type SWRSubscriptionHook = ( - key: Key, - subscribe: SWRSubscription, - config?: SWRConfiguration -) => SWRSubscriptionResponse +export interface SWRSubscriptionHook { + ( + key: SWRKey, + subscribe: SWRSubscription, + config?: SWRConfiguration + ): SWRSubscriptionResponse +} // [subscription count, disposer] type SubscriptionStates = [Map, Map void>] diff --git a/test/type/fetcher.ts b/test/type/fetcher.ts index 697d99daf..0c16f1403 100644 --- a/test/type/fetcher.ts +++ b/test/type/fetcher.ts @@ -1,5 +1,6 @@ import useSWR from 'swr' import useSWRInfinite from 'swr/infinite' +import useSWRSubscription from 'swr/subscription' import { expectType, truthy } from './utils' import type { Equal } from '@type-challenges/utils' @@ -22,6 +23,21 @@ export function useDataErrorGeneric() { }, key => key ) + useSWRSubscription<{ id: number }, { err: string }>( + 'key', + (_key, { next }) => { + expectType< + Equal< + ( + err?: { err: string } | null | undefined, + data?: { id: number } | undefined + ) => void, + typeof next + > + >(true) + return () => {} + } + ) } export function useString() { @@ -39,6 +55,11 @@ export function useString() { expectType>(true) return key }) + + useSWRSubscription('/ws', key => { + expectType>(true) + return () => {} + }) } export function useRecord() {