Skip to content

fix: Improve useSubscription typing #2525

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions subscription/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ import {
createCacheHelper
} from 'swr/_internal'

export type SWRSubscription<Data = any, Error = any> = (
key: Key,
export type SWRSubscription<
Data = any,
Error = any,
SWRKey extends Key = Key
> = (
key: SWRKey,
{ next }: { next: (err?: Error | null, data?: Data) => void }
) => () => void

Expand All @@ -18,11 +22,13 @@ export type SWRSubscriptionResponse<Data = any, Error = any> = {
error?: Error
}

export type SWRSubscriptionHook<Data = any, Error = any> = (
key: Key,
subscribe: SWRSubscription<Data, Error>,
config?: SWRConfiguration
) => SWRSubscriptionResponse<Data, Error>
export interface SWRSubscriptionHook {
<Data = any, Error = any, SWRKey extends Key = Key>(
key: SWRKey,
subscribe: SWRSubscription<Data, Error, SWRKey>,
config?: SWRConfiguration
): SWRSubscriptionResponse<Data, Error>
}

// [subscription count, disposer]
type SubscriptionStates = [Map<string, number>, Map<string, () => void>]
Expand Down
21 changes: 21 additions & 0 deletions test/type/fetcher.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand All @@ -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() {
Expand All @@ -39,6 +55,11 @@ export function useString() {
expectType<Equal<'/api/user', typeof key>>(true)
return key
})

useSWRSubscription('/ws', key => {
expectType<Equal<'/ws', typeof key>>(true)
return () => {}
})
}

export function useRecord() {
Expand Down