option-fetcher.ts
Overview
The option-fetcher.ts file is a TypeScript utility module designed to demonstrate and test typed data fetching patterns using the useSWR and useSWRInfinite hooks from the SWR library. It focuses on verifying the correctness of TypeScript types in various complex key and fetcher configurations, ensuring strict type safety and inference when using SWR for data fetching.
This file primarily contains a series of utility functions that wrap calls to useSWR or useSWRInfinite with different types of keys such as strings, records, tuples, and readonly tuples. It uses type assertions and custom type-check utilities to guarantee that the keys passed to fetchers match the expected types, facilitating robust type-safe SWR usage.
Detailed Explanation of Functions
Each exported function demonstrates a specific pattern of using SWR hooks with different key types and return types. These functions do not return values themselves but are designed to validate type inference and fetcher signatures.
Utility Imports Used
useSWR: Hook for data fetching with a single key.useSWRInfinite: Hook for paginated/infinite loading data fetching.expectType: Utility to assert that two types are equal (used for compile-time type testing).truthy: A utility that returns a boolean, used for conditional key presence.Equal: Type utility to compare types for equality.
1. useDataErrorGeneric()
Demonstrates basic usage of useSWR and useSWRInfinite with generic type parameters manually specified.
Uses:
useSWR<{ id: number }> with a static fetcher returning an object.
useSWR<string, any> with a fetcher that returns the key.
useSWRInfinite<number[]> with a fetcher echoing the key.
Parameters: None
Returns: None
Usage: Used as a baseline to test generic parameter usage with SWR.
2. useString()
Tests useSWR with string keys, including conditional keys (null or false to disable fetching).
Conditional keys tested with
truthy()to verify type inference on optional keys.Fetcher functions confirm that the key type is
'string'or the literal'/api/user'.
Parameters: None
Returns: None
Example:
useString()
3. useRecord()
Tests useSWR with complex object keys (Record types), including nested objects.
Keys are objects
{ a: string; b: { c: string; d: number } }.Conditional key presence with
nullorfalse.Fetchers validate the exact structure of the key.
4. useTuple()
Tests useSWR with tuple keys containing an object and an array.
Key shape:
[{ a: string; b: { c: string } }, (string | number)[]]Conditional keys tested.
Ensures tuple types are correctly inferred and passed to fetchers.
5. useReadonlyTuple()
Tests useSWR with readonly tuple keys (immutable tuples).
Uses
as constassertion to create readonly tuples.Validates that fetchers receive keys with literal and readonly properties.
6. useReturnString()
Demonstrates usage of function keys returning strings, with conditional returns (null or false).
Uses
useSWRanduseSWRInfinitewith function keys.Validates that keys passed to fetchers are typed as strings.
useSWRInfinitekeys depend on the page index and previous page data.
7. useReturnRecord()
Similar to useReturnString() but with function keys returning objects (records).
Key shape:
{ index: number; endPoint: string }Supports conditional keys (
nullorfalse).Validates fetcher key type correctness.
Uses
useSWRInfiniteto demonstrate paginated fetching with object keys.
8. useReturnTuple()
Tests function keys returning tuples, combining objects and arrays.
Conditional keys supported.
Includes
useSWRInfinitewith paginated keys modifying object fields.Fetchers validate tuple types.
9. useReturnReadonlyTuple()
Extends useReturnTuple() by testing readonly tuple keys returned from functions.
Conditional keys with
nullorfalse.Uses
as constfor readonly tuple keys.Validates fetcher key types with readonly properties.
Includes
useSWRInfinitewith readonly tuples.
Important Implementation Details
Type Safety: The core purpose of this file is to ensure correct type inference and type safety when using SWR hooks with various complex key types. It uses exhaustive tests combining literal types, records, tuples, readonly tuples, conditional keys (
nullorfalse), and function keys.Conditional Keys: The use of
truthy()to conditionally disable fetching by returningnullorfalseas keys is demonstrated repeatedly. This aligns with SWR's behavior to skip fetches when keys are falsy.Fetcher Functions: Each fetcher uses
expectTypeandEqualutilities to assert the expected type of the key parameter at compile-time, ensuring no type mismatches.Infinite Loading:
useSWRInfiniteis used with keys depending on the page index and previous page data, demonstrating paginated data fetching with typed keys.Readonly Tuples: Usage of
as constto produce deeply readonly tuples and verify that SWR hooks properly infer these readonly types.
Interaction With Other Parts of the System
SWR Library: This file depends heavily on the SWR (
stale-while-revalidate) library's React hooksuseSWRanduseSWRInfiniteto perform data fetching.Type Utility Modules: It imports type utilities like
expectType,truthy, andEqualfrom local./utilsand@type-challenges/utils. These are used solely for type assertion and compile-time validation, not runtime logic.API Endpoints: The keys such as
'/api/user'and'/api/'represent placeholders for API endpoints. This file simulates fetchers returning these keys or structured data to test type inference rather than perform real network fetching.Testing and Validation: This file likely serves as a test or example module within the project to validate type correctness for developers integrating SWR with complex typed keys.
Usage Example
Below is an example snippet of how one of these functions might be used in a React component context for type testing:
import React from 'react'
import { useString } from './option-fetcher'
function UserComponent() {
useString()
return <div>User data is fetched with strict typing</div>
}
Mermaid Class Diagram
classDiagram
class option-fetcher {
<<utility>>
+useDataErrorGeneric()
+useString()
+useRecord()
+useTuple()
+useReadonlyTuple()
+useReturnString()
+useReturnRecord()
+useReturnTuple()
+useReturnReadonlyTuple()
}
Diagram Explanation:
This diagram shows option-fetcher.ts as a utility module exporting multiple functions. Each function represents a different typed data fetching pattern using useSWR or useSWRInfinite. There are no classes or properties, only exported functions.
Summary
option-fetcher.ts is a specialized TypeScript module for validating and demonstrating strongly-typed usage of SWR hooks with various key types and fetcher signatures. It serves as a comprehensive testbed for ensuring that complex key types (strings, records, tuples, readonly tuples) and conditional presence are correctly handled by the SWR library and TypeScript compiler, providing developers with confidence in type safety for their data fetching logic.