From fed98f1e0972f67574453b0df5191e80a9d978b7 Mon Sep 17 00:00:00 2001 From: Yuta Osawa Date: Fri, 24 Mar 2023 00:31:54 +0900 Subject: [PATCH 1/2] fix: allow passing generics to useSWRSubscription --- subscription/index.ts | 8 ++++++-- test/type/fetcher.ts | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/subscription/index.ts b/subscription/index.ts index bc8f8e21c..db760b6ab 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 diff --git a/test/type/fetcher.ts b/test/type/fetcher.ts index 697d99daf..644d6802a 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() { From 45269fd18f54cfa6be9a324dd40ff3d3596617bd Mon Sep 17 00:00:00 2001 From: Yuta Osawa Date: Fri, 24 Mar 2023 00:35:41 +0900 Subject: [PATCH 2/2] fix: allow infering key type of useSWRSubscription --- subscription/index.ts | 12 +++++++----- test/type/fetcher.ts | 5 +++++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/subscription/index.ts b/subscription/index.ts index db760b6ab..4323c78c1 100644 --- a/subscription/index.ts +++ b/subscription/index.ts @@ -22,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 644d6802a..0c16f1403 100644 --- a/test/type/fetcher.ts +++ b/test/type/fetcher.ts @@ -55,6 +55,11 @@ export function useString() { expectType>(true) return key }) + + useSWRSubscription('/ws', key => { + expectType>(true) + return () => {} + }) } export function useRecord() {