TypeScript & JavaScript Usage

Whether you are writing strict TypeScript, modern ES Module JavaScript, or legacy CommonJS scripts, react-native-fetch-client supports all module formats out of the box.


1. Strict TypeScript Generics

Every HTTP method (.get<T>(), .post<T>(), etc.) accepts a type parameter representing the decoded response data.

types.ts
typescript
import { createClient, type HttpResponse } from 'react-native-fetch-client';

interface Article {
  slug: string;
  title: string;
  views: number;
}

const api = createClient({ baseURL: 'https://api.myblog.com' });

// 1. Generic typed response
const res: HttpResponse<Article> = await api.get<Article>('/articles/first-post');
console.log(res.data.title);

// 2. Read the parsed data from the default response envelope
console.log(res.data.views);
Unwrap and TypeScript
At runtime, unwrap: true returns response data directly. The current method declarations still type that result as HttpResponse<T>; use the default envelope in TypeScript or provide a typed wrapper.

2. Modern JavaScript (ES Modules)

In React Native (Hermes/Metro), Expo, Webpack, Vite, or Node with "type": "module", use standard import:

javascript
import { createClient } from 'react-native-fetch-client';

const api = createClient({ baseURL: 'https://api.example.com' });

const response = await api.get('/items');
console.log(response.status, response.data);

3. Node.js CommonJS (require)

For legacy Node.js scripts or backend services using CommonJS, dual CJS bundles are provided at dist/index.cjs:

javascript
const { createClient } = require('react-native-fetch-client');

const api = createClient({ baseURL: 'https://api.example.com' });

async function run() {
  const response = await api.get('/items');
  console.log(response.data);
}

run();
Dual Package Hazard Free
The build system produces completely isolated CJS and ESM entry points with dedicated TypeScript declaration maps (index.d.ts and index.d.cts), preventing dual-package hazards.