A Typed Fetch Wrapper in TypeScript
Overview
A fetch wrapper centralises all HTTP logic in one place — base URL, headers, JSON serialisation — so every call site stays clean and consistent. This guide builds a FetchWrapper class in TypeScript that is fully generic: callers declare the expected response type and TypeScript enforces it at compile time.
The JavaScript Starting Point
The original JavaScript class looks like this:
class FetchWrapper {
constructor(baseURL) {
this.baseURL = baseURL
}
get(endpoint) {
return fetch(this.baseURL + endpoint).then((response) => response.json())
}
put(endpoint, body) {
return this.#send('put', endpoint, body)
}
post(endpoint, body) {
return this.#send('post', endpoint, body)
}
delete(endpoint, body) {
return this.#send('delete', endpoint, body)
}
#send(method, endpoint, body) {
return fetch(this.baseURL + endpoint, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}).then((response) => response.json())
}
}
This works in JavaScript but has no type safety — every method returns Promise<any>. Callers have no idea what shape the response will have, and typos in response properties are silent at runtime.
The TypeScript Version
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
class FetchWrapper {
readonly #baseURL: string
constructor(baseURL: string) {
this.#baseURL = baseURL
}
get<T>(endpoint: string): Promise<T> {
return fetch(this.#baseURL + endpoint).then((response) =>
this.#parseResponse<T>(response),
)
}
post<T>(endpoint: string, body: unknown): Promise<T> {
return this.#send<T>('POST', endpoint, body)
}
put<T>(endpoint: string, body: unknown): Promise<T> {
return this.#send<T>('PUT', endpoint, body)
}
delete<T>(endpoint: string, body?: unknown): Promise<T> {
return this.#send<T>('DELETE', endpoint, body)
}
#send<T>(method: HttpMethod, endpoint: string, body?: unknown): Promise<T> {
return fetch(this.#baseURL + endpoint, {
method,
headers: { 'Content-Type': 'application/json' },
body: body !== undefined ? JSON.stringify(body) : undefined,
}).then((response) => this.#parseResponse<T>(response))
}
async #parseResponse<T>(response: Response): Promise<T> {
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
return response.json() as Promise<T>
}
}
What Each Type Decision Does
readonly #baseURL: string
readonly prevents the base URL from being reassigned after construction. The # prefix is JavaScript's native private field — inaccessible outside the class at runtime (not just at compile time like TypeScript's private keyword).
const api = new FetchWrapper('https://api.example.com')
api.#baseURL = 'https://evil.com' // ❌ Error — private field
type HttpMethod
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
A union of string literals. Passing an arbitrary string to #send is now a compile-time error:
this.#send('get', endpoint, body) // ❌ Error — 'get' is not assignable to HttpMethod