TypeScript Guide
BoltFetch was designed from day one to embrace TypeScript's most powerful features. Using BoltFetch means your network boundaries are as strictly typed as your internal business logic.
1. Generic Response Typing
The most common use case is defining the shape of the data you expect to receive from an API. You pass this interface as a generic type argument to the request method.
typescriptimport { boltfetch } from "boltfetch"; interface UserProfile { id: string; email: string; preferences: { theme: 'dark' | 'light'; notificationsEnabled: boolean; }; } // Pass the interface to the generic get<T> method const response = await boltfetch.get<UserProfile>('https://api.example.com/profile'); if (response.success) { // TypeScript knows response is BoltFetchResponse<UserProfile> // Hover over 'response.data' below, and you'll see it is perfectly typed! console.log(`User prefers ${response.data.preferences.theme} theme.`); } else { // TypeScript knows response is BoltFetchError console.error("Failed:", response.message); }
2. Typing Specific Error Payloads
APIs often return specific, structured error objects when a request fails (for instance, a 400 Bad Request might return a map of validation errors).
You can access these via the moreInfo property on the BoltFetchError. While moreInfo is any by default, you can easily cast it or define type guards if you know your API's error structure.
typescriptinterface ApiValidationErrors { fields: Record<string, string[]>; errorCode: string; } const response = await boltfetch.post<CreateUserResponse>('/api/users', payload); if (!response.success) { if (response.status === 400 && response.moreInfo) { // Cast moreInfo to your expected error structure const errors = response.moreInfo as ApiValidationErrors; const emailErrors = errors.fields['email']; if (emailErrors) { console.warn("Email validation failed:", emailErrors.join(", ")); } } }
3. Type Narrowing
Because BoltFetch returns a single object containing a success boolean, it relies on TypeScript's Discriminated Unions to narrow the type.
When success === true, the object is recognized as a BoltFetchResponse, making the .data property accessible.
When success === false, the object is recognized as a BoltFetchError, making the .message and .moreInfo properties accessible, while .data is not.
This completely eliminates the need to cast the catch(e) error parameter that standard fetch uses.