types.ts


Overview

The types.ts file defines TypeScript type aliases and interfaces that establish the contract for implementing subscription-based real-time data fetching within the SWR (stale-while-revalidate) ecosystem. It provides strongly typed definitions for subscription options, subscription function signatures, subscription hook responses, and the subscription hook itself.

These types enable developers to create subscription hooks that integrate with SWR’s caching and revalidation mechanisms, supporting live updates from external data sources like WebSocket streams or event emitters in a type-safe manner.

This file does not contain executable code but rather the foundational typings to ensure consistency, clarity, and flexibility in subscription implementations.


Detailed Type Definitions

1. SWRSubscriptionOptions<Data = any, Error = any>

Description

Represents the options object passed to a subscription function. It contains a single method next that serves as a callback to deliver new data or error updates from the subscription source back to SWR’s internal state.

Properties

Name

Type

Description

next

[(err?: Error \

null, data?: Data \

Usage Example

const options: SWRSubscriptionOptions<User, Error> = {
  next: (err, data) => {
    if (err) {
      console.error(err)
    } else {
      // Update UI or cache with new data
      console.log(data)
    }
  }
}

2. SWRSubscription<SWRSubKey extends Key = Key, Data = any, Error = any>

Description

A generic type alias that defines the signature of a subscription function. The function sets up a subscription (e.g., WebSocket, event listener) for a given key and delivers updates via the next callback.

This type is conditionally defined based on the shape of the subscription key SWRSubKey:

Signature

SWRSubKey extends () => infer Arg | null | undefined | false
  ? (key: Arg, { next }: SWRSubscriptionOptions<Data, Error>) => void
  : SWRSubKey extends null | undefined | false
  ? never
  : SWRSubKey extends infer Arg
  ? (key: Arg, { next }: SWRSubscriptionOptions<Data, Error>) => void
  : never

Parameters

Name

Type

Description

key

Arg

The resolved subscription key or parameter extracted from the key function.

{ next }

SWRSubscriptionOptions<Data, Error>

The subscription options object containing the next callback to push updates.

Return Value

void — The subscription function sets up the subscription side-effect and handles updates through next. Unsubscribe function is expected to be handled externally or returned by the actual implementation (some implementations may return a cleanup function, but this type only covers the signature).

Usage Example

const subscribe: SWRSubscription<string, User, Error> = (key, { next }) => {
  const ws = new WebSocket(`wss://example.com/user/${key}`)
  
  ws.onmessage = event => {
    const data = JSON.parse(event.data) as User
    next(null, data)  // Push new data
  }
  
  ws.onerror = error => {
    next(error)
  }
  
  // Cleanup function could be returned here in implementation
}

3. SWRSubscriptionResponse<Data = any, Error = any>

Description

Type describing the response object from a subscription hook. It contains optional data and error properties, following the typical SWR hook return shape.

Properties

Name

Type

Description

data

Data (optional)

The latest data received from the subscription.

error

Error (optional)

The latest error received from the subscription, if any.

Usage Example

const response: SWRSubscriptionResponse<User, Error> = {
  data: { id: 1, name: 'Alice' },
  error: undefined
}

4. SWRSubscriptionHook

Description

A generic type defining the signature of the hook exposing the subscription API. It wraps the subscription function and manages the subscription lifecycle and SWR cache integration.

Signature

<
  Data = any,
  Error = any,
  SWRSubKey extends Key = Key
>(
  key: SWRSubKey,
  subscribe: SWRSubscription<SWRSubKey, Data, Error>,
  config?: SWRConfiguration
) => SWRSubscriptionResponse<Data, Error>

Parameters

Name

Type

Description

key

SWRSubKey

The key identifying the subscription. Can be a function or static key.

subscribe

SWRSubscription<SWRSubKey, Data, Error>

The subscription function to set up real-time updates.

config

SWRConfiguration (optional)

Optional SWR configuration object, supporting cache, revalidation, and other SWR options.

Return Value

SWRSubscriptionResponse<Data, Error> — The hook returns an object containing data and error that React components can use reactively.

Usage Example

const { data, error } = useSWRSubscription<User, Error, string>(
  'user-123',
  (key, { next }) => {
    const ws = new WebSocket(`wss://api.example.com/users/${key}`)
    ws.onmessage = event => next(null, JSON.parse(event.data))
    ws.onerror = err => next(err)
    return () => ws.close()  // Cleanup on unsubscribe
  },
  { revalidateOnFocus: true }
)

Important Implementation Details


Interaction with the System


Mermaid Diagram: Subscription Types Structure

classDiagram
    class SWRSubscriptionOptions {
        +next(err?: Error|null, data?: Data|MutatorCallback<Data>): void
    }

    class SWRSubscription {
        <<type>>
        +invoke(key: Arg, options: SWRSubscriptionOptions): void
    }

    class SWRSubscriptionResponse {
        +data: Data
        +error: Error
    }

    class SWRSubscriptionHook {
        <<type>>
        +invoke(key: SWRSubKey, subscribe: SWRSubscription, config?: SWRConfiguration): SWRSubscriptionResponse
    }

    SWRSubscriptionOptions <.. SWRSubscription : uses
    SWRSubscription --> SWRSubscriptionHook : parameter
    SWRSubscriptionResponse <-- SWRSubscriptionHook : returns

Summary

The types.ts file defines core TypeScript types that formalize the contract for subscription-based real-time data fetching in the SWR ecosystem. It declares:

These types enable developers to implement strongly typed, flexible, and scalable subscription hooks that fit seamlessly into SWR’s middleware architecture, supporting live data updates with automatic lifecycle and cache management.


References


End of types.ts documentation.