createFetchClientWithContext function creates a factory for createFetchClient with custom TypeScript context types. This enables advanced type safety features like custom data types, error types, and configuration defaults at the type level.
Function Signature
Type Parameters
Custom context type that defines type-level defaults for all clients created by this factory.
Context Properties
Default type for successful response data. Used when no explicit type is provided to
callApi.Default type for error response data. Used for HTTP error responses.
Default result mode for all requests. Affects return type structure.
Return Type
Returns a
createFetchClient function that inherits the custom context types. The returned factory has the same signature as the standard createFetchClient, but with your custom types as defaults.Usage Examples
Basic Context with Custom Error Type
Context with Standard Response Wrapper
Context for Different API Versions
Context with Organization-Wide Standards
Context with Custom Result Mode Default
Multiple Contexts for Different Services
Type Inference
Context types flow through the entire call chain:When to Use
UsecreateFetchClientWithContext when you need:
- Consistent error types: Your API has a standard error format
- Response wrappers: All responses follow a common structure
- Multiple API versions: Different type defaults per version
- Organization standards: Enforce consistent types across teams
- Default result mode: Always use
resultmode for explicit error handling - Library/SDK development: Create typed clients for external users
createFetchClient is usually sufficient.
Best Practices
- Define context once: Create a single factory per API or service
- Export the factory: Share it across your codebase
- Document error types: Make it clear what errors can occur
- Use discriminated unions: For APIs with multiple response formats
- Version your contexts: Create new contexts for API version changes
Related
- callApi - Default client instance
- createFetchClient - Create client without custom context