typedFetch Function
Signature
typescript
typedFetch<T, E extends ClientErrors>(url: FetchParams[0], options?: FetchParams[1])
T
: Expected response body typeE
: Specific client error classes (optional)url
: URL string or Request object (same as native fetch)options
: RequestInit options (same as native fetch)
Returns a Promise with { response: TypedResponse<T> | null, error: E | ServerErrors | NetworkError | null }
Fetch API Compatibility
The typedFetch
function has identical API to the native fetch()
function. This means:
- ✅ All fetch options work:
method
,headers
,body
,credentials
,cache
, etc. - ✅ Full AbortController support via
signal
option - ✅ Request timeout using
AbortSignal.timeout()
- ✅ Same parameter types as native fetch
- ✅ Drop-in replacement for existing fetch calls
Examples with Fetch Features
Request Cancellation
typescript
const controller = new AbortController();
const { response, error } = await typedFetch<User[]>('/api/users', {
signal: controller.signal
});
// Cancel the request
controller.abort();
Request Timeout
typescript
const { response, error } = await typedFetch<User[]>('/api/users', {
signal: AbortSignal.timeout(5000) // 5 second timeout
});
Advanced Options
typescript
const { response, error } = await typedFetch<User>('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
},
body: JSON.stringify(userData),
credentials: 'include',
cache: 'no-cache',
signal: controller.signal
});