From 1be78f778089c38ae20170550f81c35e37c39691 Mon Sep 17 00:00:00 2001 From: Yixuan Xu Date: Thu, 21 Apr 2022 06:13:14 +0800 Subject: [PATCH] type: extends useConfig cache interface (#1938) --- src/types.ts | 7 ++++--- src/utils/use-swr-config.ts | 6 ++++-- test/type/config.ts | 12 ++++++++++++ 3 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 test/type/config.ts diff --git a/src/types.ts b/src/types.ts index 0dea512cd..37638f555 100644 --- a/src/types.ts +++ b/src/types.ts @@ -17,8 +17,8 @@ export type Fetcher< : never // Configuration types that are only used internally, not exposed to the user. -export interface InternalConfiguration { - cache: Cache +export interface InternalConfiguration { + cache: T mutate: ScopedMutator } @@ -77,7 +77,8 @@ export interface PublicConfiguration< isVisible: () => boolean } -export type FullConfiguration = InternalConfiguration & PublicConfiguration +export type FullConfiguration = + InternalConfiguration & PublicConfiguration export type ProviderConfiguration = { initFocus: (callback: () => void) => (() => void) | void diff --git a/src/utils/use-swr-config.ts b/src/utils/use-swr-config.ts index 24814006e..a12ec7b73 100644 --- a/src/utils/use-swr-config.ts +++ b/src/utils/use-swr-config.ts @@ -2,8 +2,10 @@ import { useContext } from 'react' import { defaultConfig } from './config' import { SWRConfigContext } from './config-context' import { mergeObjects } from './helper' -import { FullConfiguration } from '../types' +import { FullConfiguration, Cache } from '../types' -export const useSWRConfig = (): FullConfiguration => { +export const useSWRConfig = < + T extends Cache = Map +>(): FullConfiguration => { return mergeObjects(defaultConfig, useContext(SWRConfigContext)) } diff --git a/test/type/config.ts b/test/type/config.ts new file mode 100644 index 000000000..54a9ff9f7 --- /dev/null +++ b/test/type/config.ts @@ -0,0 +1,12 @@ +import { useSWRConfig, Cache } from 'swr' +import { expectType } from './utils' + +interface CustomCache extends Cache { + reset(): void +} + +export function useTestCache() { + expectType>(useSWRConfig().cache) + expectType>(useSWRConfig>().cache) + expectType(useSWRConfig().cache) +}