Skip to content

Commit

Permalink
type: extends useConfig cache interface (vercel#1938)
Browse files Browse the repository at this point in the history
  • Loading branch information
promer94 authored and himanshiLt committed Apr 26, 2022
1 parent bff2df6 commit 1be78f7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
7 changes: 4 additions & 3 deletions src/types.ts
Expand Up @@ -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<T extends Cache = Cache> {
cache: T
mutate: ScopedMutator
}

Expand Down Expand Up @@ -77,7 +77,8 @@ export interface PublicConfiguration<
isVisible: () => boolean
}

export type FullConfiguration = InternalConfiguration & PublicConfiguration
export type FullConfiguration<T extends Cache = Cache> =
InternalConfiguration<T> & PublicConfiguration

export type ProviderConfiguration = {
initFocus: (callback: () => void) => (() => void) | void
Expand Down
6 changes: 4 additions & 2 deletions src/utils/use-swr-config.ts
Expand Up @@ -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<string, any>
>(): FullConfiguration<T> => {
return mergeObjects(defaultConfig, useContext(SWRConfigContext))
}
12 changes: 12 additions & 0 deletions test/type/config.ts
@@ -0,0 +1,12 @@
import { useSWRConfig, Cache } from 'swr'
import { expectType } from './utils'

interface CustomCache<Data = any> extends Cache<Data> {
reset(): void
}

export function useTestCache() {
expectType<Map<string, any>>(useSWRConfig().cache)
expectType<Map<string, number>>(useSWRConfig<Map<string, number>>().cache)
expectType<CustomCache>(useSWRConfig<CustomCache>().cache)
}

0 comments on commit 1be78f7

Please sign in to comment.