Skip to content
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

type: extends useConfig cache interface #1938

Merged
merged 1 commit into from Apr 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
}