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 |
|---|---|---|
| [(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:
If
SWRSubKeyis a function returning a key argument (possibly nullable or falsy), the subscription function receives the unwrapped argument.If
SWRSubKeyisnull,undefined, orfalse, subscription is disabled (type resolves tonever).Otherwise, the subscription function receives the key as is.
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 |
|---|---|---|
|
| The resolved subscription key or parameter extracted from the key function. |
|
| The subscription options object containing the |
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 |
|---|---|---|
|
| The latest data received from the subscription. |
|
| 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 |
|---|---|---|
|
| The key identifying the subscription. Can be a function or static key. |
|
| The subscription function to set up real-time updates. |
|
| 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
Conditional Key Typing:
TheSWRSubscriptiontype uses conditional types to adapt the subscription function signature depending on whether the key is a function returning a parameter or a direct key. This enables flexible subscription patterns such as parameterized or conditional subscriptions.Next Callback:
Thenextfunction inSWRSubscriptionOptionssupports both direct data and mutator callbacks (MutatorCallback<Data>), allowing advanced cache mutation strategies beyond simple data replacement.Generic Parameters:
All types are generic overDataandErrorto support any data shape and error object, making the subscription system widely applicable.Integration with SWR:
TheSWRSubscriptionHooktype ties the subscription function with SWR’s configuration and response format, ensuring seamless integration with SWR’s core hooks and middleware.
Interaction with the System
This typing file is imported and used by the subscription middleware and hooks implementation files (e.g.,
src/subscription/index.ts), which implement the runtime behavior of subscription lifecycle management.The types ensure that all subscription-related functions and hooks conform to a consistent API, aiding static typing and developer tooling support.
By defining these types separately, the system supports modular development, where the subscription middleware can evolve independently of the core SWR library, while preserving type safety.
The subscription system integrates with the SWR cache and mutation APIs to propagate real-time updates to React components subscribed to specific keys.
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:
The shape and behavior of subscription options with the
nextupdate callback.The adaptable subscription function signature that accommodates different key forms.
The subscription hook response containing reactive
dataanderror.The subscription hook type integrating the subscription logic with SWR’s configuration and response model.
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.