preload.ts

Overview

The preload.ts file is a testing utility module designed to verify the type correctness and behavior of the preload function from the swr library. It primarily focuses on ensuring that TypeScript type inference and generic typing work as expected when using preload with different argument signatures.

This file does not implement business logic or application features itself but serves as a type safety check within the development workflow, helping maintain robust typings when preloading data with SWR (stale-while-revalidate) patterns.


Detailed Explanation

Imported Entities


Function: testPreload

export function testPreload(): void

Purpose

Runs a series of compile-time assertions to validate the behavior and type inference of the preload function with various usages and parameters.

Parameters

Returns

Usage

testPreload is intended to be invoked during development or in a type-testing context to verify typings. It doesn't produce runtime output but ensures TypeScript types behave as expected.


Breakdown of Test Cases Inside testPreload

  1. Basic preload with key and async fetcher returning a constant string

    const data1 = preload('key', () => Promise.resolve('value' as const))
    expectType<Equal<Promise<'value'>, typeof data1>>(true)
    
    • Calls preload with a string key and a fetcher returning a resolved Promise of 'value'.

    • Asserts that data1 is inferred as Promise<'value'>.

  2. Preload with key factory function and synchronous fetcher

    const data2 = preload(
      () => 'key',
      () => 'value' as const
    )
    expectType<Equal<'value', typeof data2>>(true)
    
    • Uses a function returning the key instead of a literal key.

    • The fetcher returns 'value' synchronously.

    • Asserts that data2 is inferred as 'value'.

  3. Preload with explicit generic parameter

    const data3 = preload<'value'>(
      () => 'key',
      () => 'value' as const
    )
    expectType<Equal<'value' | Promise<'value'>, typeof data3>>(true)
    
    • Specifies return type 'value' as a generic parameter.

    • Due to generic typing, the inferred type is a union of 'value' and Promise<'value'>.

    • This highlights a limitation in type inference when generics are used explicitly.

  4. Preload with key and fetcher that asserts key type

    preload('key', key => {
      expectType<Equal<'key', typeof key>>(true)
    })
    
    • Tests that the fetcher parameter key is inferred as the literal type 'key'.

  5. Preload with generic parameter and fetcher

    preload<'value'>(
      'key',
      (
        // @ts-expect-error -- infered any implicitly
        key
      ) => {
        return 'value' as const
      }
    )
    
    • Demonstrates a TypeScript error scenario where key is implicitly any due to the generic parameter usage.

    • The comment disables the expected error for testing purposes.

  6. Preload with tuple key and fetcher

    preload(['key', 1], keys => {
      expectType<Equal<[string, number], typeof keys>>(true)
    })
    
    • Uses an array tuple as a key.

    • The fetcher receives the tuple key [string, number].

    • Asserts correct tuple typing.

  7. Preload with key factory returning a literal type

    preload(
      () => 'key' as const,
      key => {
        expectType<Equal<'key', typeof key>>(true)
      }
    )
    
    • Similar to case 4 but with the key returned as a constant literal.

    • Ensures fetcher key parameter is inferred correctly as 'key'.


Important Implementation Details


Interaction with Other Parts of the System


Visual Diagram

flowchart TD
    A[testPreload()] --> B[preload(key, fetcher)]
    A --> C[preload(keyFactory, fetcher)]
    A --> D[preload with generic type]
    A --> E[preload with tuple key]
    B --> F[Checks return type matches Promise<'value'>]
    C --> G[Checks return type matches 'value']
    D --> H[Checks union of 'value' | Promise<'value'>]
    E --> I[Checks tuple key typing]

    classDef func fill:#f9f,stroke:#333,stroke-width:1px
    class A,B,C,D,E func

Summary

The preload.ts file is a TypeScript-centric test module that validates the type correctness and inference behavior of the preload function from the swr package. It uses a variety of test cases to check typings with literal keys, key factories, generic parameters, and tuple keys, ensuring strict and expected type behavior. This enhances type safety and developer confidence when preloading data in the broader application context.


Example Usage of preload (outside of this test file)

import { preload } from 'swr'

// Preload asynchronously with a key and fetcher returning a promise
const promise = preload('user-123', () => fetchUserData('user-123'))

// Preload synchronously with key factory and fetcher
const data = preload(() => 'settings', () => getCachedSettings())

This example illustrates typical real-world usage scenarios verified by the tests in preload.ts.