subscription.ts


Overview

The subscription.ts file serves as a comprehensive test suite for the useSWRSubscription hook provided by the swr/subscription library. It extensively demonstrates and verifies the type safety and usage patterns of this hook across various forms of subscription keys and subscription functions. The file primarily focuses on TypeScript type assertions rather than runtime logic, ensuring that useSWRSubscription behaves correctly with different key types and subscription implementations.

This file is particularly useful for validating the integration of useSWRSubscription with custom subscription logic and verifying that TypeScript typings align with expected usage scenarios. It acts as both a usage example and a type correctness checker for consuming components or hooks within a larger application.


Detailed Explanation

Imports


Function: useTestSubscription()

export function useTestSubscription(): void

Purpose

This function demonstrates multiple invocations of useSWRSubscription with various forms of keys and subscription callbacks. It performs type assertions on keys and returned data/error to ensure type correctness.

Parameters

Returns

Description and Usage

Inside useTestSubscription, useSWRSubscription is called multiple times with:

Each subscription callback receives:

The subscription callback returns a cleanup function () => {}, conforming to the expected signature.

Finally, the function declares an explicit SWRSubscription type subscription function sub and calls useSWRSubscription with it, validating inferred types of data and error returned from the hook.

Example Usage

useSWRSubscription(
  'key',
  (key, { next }) => {
    // key is expected to be 'key'
    // Implement subscription logic here...
    return () => {
      // Cleanup logic
    }
  }
)

Important Implementation Details


Interaction with Other Parts of the System


Mermaid Class Diagram

This diagram illustrates the structure of the primary function and the relationship with the imported types and functions.

classDiagram
    class useTestSubscription {
        +void()
    }

    class useSWRSubscription {
        <<imported function>>
        +useSWRSubscription(key: KeyType, subscription: SWRSubscription): { data, error }
    }

    class SWRSubscription {
        <<type>>
        +subscription(key: KeyType, options: SWRSubscriptionOptions): () => void
    }

    class SWRSubscriptionOptions {
        <<type>>
        +next: Function
    }

    class utils {
        <<module>>
        +expectType<T>(value: any): void
        +truthy(): boolean
    }

    useTestSubscription ..> useSWRSubscription : calls
    useTestSubscription ..> SWRSubscription : uses
    useTestSubscription ..> SWRSubscriptionOptions : uses
    useTestSubscription ..> utils : uses

Summary