types.ts


Overview

The types.ts file is a core TypeScript declaration module within the SWR (stale-while-revalidate) data fetching library ecosystem. It primarily defines the comprehensive type system and interfaces that underpin SWR’s behavior, configuration options, and internal state management. This file establishes the shapes and contracts for:

By defining these types, types.ts enables strong typing and IntelliSense support throughout the SWR codebase and for library users integrating SWR with TypeScript.


Detailed Descriptions

Type Aliases and Utility Types

GlobalState

type GlobalState = [
  Record<string, RevalidateCallback[]>, // EVENT_REVALIDATORS
  Record<string, [number, number]>, // MUTATION timestamps: [start_ts, end_ts]
  Record<string, [any, number]>, // FETCH cache: [data, timestamp]
  Record<string, FetcherResponse<any>>, // PRELOAD cache
  ScopedMutator, // Mutator function for updating cache
  (key: string, value: any, prev: any) => void, // Setter function for cache updates
  (key: string, callback: (current: any, prev: any) => void) => () => void // Subscriber to cache changes
]

FetcherResponse<Data = unknown>

type FetcherResponse<Data = unknown> = Data | Promise<Data>

BareFetcher<Data = unknown>

type BareFetcher<Data = unknown> = (...args: any[]) => FetcherResponse<Data>

Fetcher<Data = unknown, SWRKey extends Key = Key>

A conditional type that infers the fetcher's argument type based on the SWR key.


BlockingData<Data, Options>

Determines if data loading should block (e.g., React Suspense mode):


Interfaces

InternalConfiguration

interface InternalConfiguration {
  cache: Cache
  mutate: ScopedMutator
}

PublicConfiguration<Data, Error, Fn>

Defines all user-exposed configuration options for SWR hooks.

Key properties include:

Example usage:

const config: PublicConfiguration<User, Error> = {
  errorRetryInterval: 5000,
  revalidateOnFocus: true,
  fetcher: (url) => fetch(url).then(res => res.json()),
  onError: (err, key) => console.error(`Error fetching ${key}`, err),
}

FullConfiguration<Data, Error, Fn>

Combines internal and public configurations.


ProviderConfiguration

Configuration related to event initialization:


SWRHook

The generic function type signature of the useSWR hook.

Example usage:

const { data, error, mutate } = useSWR<User>('api/user', fetcher, { suspense: true })

Middleware

A higher-order function that wraps an SWRHook to extend or modify its behavior.

Signature:

type Middleware = (
  useSWRNext: SWRHook
) => <Data, Error>(
  key: Key,
  fetcher: BareFetcher<Data> | null,
  config: SWRConfiguration<Data, Error, BareFetcher<Data>>
) => SWRResponse<Data, Error>

Key and Arguments Types


Mutator Types and Interfaces


SWRConfiguration

Partial configuration type combining PublicConfiguration and ProviderConfiguration with optional provider override.


SWRResponse<Data, Error, Config>

The return type of useSWR hook, containing:


Revalidation Types


Cache<Data>

Interface for cache implementations managing SWR state:


State<Data, Error>

Represents cached state per key:


Important Implementation Details and Algorithms


Interaction with Other Parts of the System


Visual Diagram: Type Structure Flowchart

flowchart TD
    A[GlobalState] -->|uses| B[RevalidateCallback[]]
    A --> C[Mutation Timestamps]
    A --> D[Fetch Cache]
    A --> E[Preload Cache]
    A --> F[ScopedMutator]
    A --> G[Setter Function]
    A --> H[Subscriber Function]

    SWRHook -->|returns| SWRResponse
    SWRResponse -->|contains| data[Data]
    SWRResponse --> error[Error]
    SWRResponse --> mutate[KeyedMutator]
    SWRResponse --> isValidating[boolean]
    SWRResponse --> isLoading[boolean]

    PublicConfig -->|includes| errorRetryInterval
    PublicConfig --> revalidateOnFocus
    PublicConfig --> fetcher
    PublicConfig --> use[Middleware[]]
    PublicConfig --> onErrorRetry

    MutatorOptions -->|controls| mutateBehavior[Mutation Behavior]
    ScopedMutator -->|overloads| mutatorSingle[Single Key]
    ScopedMutator --> mutatorMultiple[Multiple Keys]

    CacheInterface -->|defines| keysMethod
    CacheInterface --> getMethod
    CacheInterface --> setMethod
    CacheInterface --> deleteMethod

    Middleware -->|wraps| SWRHook

    Key -->|argument for| Fetcher
    Fetcher -->|returns| FetcherResponse

    SWRConfiguration -->|extends| PublicConfig
    SWRConfiguration --> ProviderConfig

    RevalidateCallback -->|handles| RevalidateEvents

    style SWRHook fill:#f9f,stroke:#333,stroke-width:1px
    style PublicConfig fill:#bbf,stroke:#333,stroke-width:1px
    style ScopedMutator fill:#bfb,stroke:#333,stroke-width:1px
    style CacheInterface fill:#fbf,stroke:#333,stroke-width:1px

Summary

The types.ts file is a comprehensive declaration module that defines the core types, interfaces, and contracts for SWR's data fetching and caching mechanism. It provides a strongly typed foundation for:

Its types enable modularity, extensibility, and robust type safety across the SWR library and its consumers, facilitating advanced features such as suspense mode, optimistic updates, and custom revalidation logic.