Header Types and Request Configuration
What you'll learn: How to type RequestInit configuration objects, especially headers, to ensure consistent and safe API client setup.
When you call fetch, the second argument is a configuration object called RequestInit. This object can contain headers, methods, credentials, and more. Without types, it's easy to misconfigure requests — misspell header names, pass invalid values, or forget required options.
Why Type Request Configuration?
Think of RequestInit like a form you fill out before sending a letter. If the form has labeled fields (types), you know exactly what goes where. Without them, you might write your return address in the stamp area.
TypeScript's built-in RequestInit type already provides basic structure, but you can create stricter, domain-specific types to enforce your API's conventions.
Typing Headers
The headers property accepts several formats: plain objects, Headers instances, or arrays of tuples. You can type them explicitly:
interface ApiHeaders {
'Content-Type': 'application/json';
'Authorization': `Bearer ${string}`;
'X-Api-Version'?: string;
}
const config: RequestInit = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer abc123',
} satisfies ApiHeaders
};
The satisfies operator ensures your header object matches your strict interface while preserving literal types.
Typing Full Request Configuration
For reusable API clients, create configuration types that enforce your requirements:
interface ApiRequestInit extends RequestInit {
headers: ApiHeaders;
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
}
function apiCall(url: string, config: ApiRequestInit): Promise<Response> {
return fetch(url, config);
}
This prevents invalid HTTP methods and ensures required headers are always present.
Key Takeaway: Typing RequestInit and headers creates self-documenting, consistent API clients that catch configuration errors at compile time, not runtime.