typescript
/

TypeScript Fetch – HTTP Requests with Types

Last Sync: Today

On this page

11
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

typescript

TypeScript Fetch – HTTP Requests with Types

What is Fetch API?

The Fetch API provides a modern interface for making HTTP requests in the browser and Node.js. TypeScript enhances it with type safety for responses and error handling.

Basic GET Request

TypeScriptRead-only
1
async function getUsers(): Promise<void> {
  const response = await fetch('https://api.example.com/users');
  const data = await response.json();
  console.log(data);
}

Typed Response

TypeScriptRead-only
1
interface User {
  id: number;
  name: string;
  email: string;
}

async function getUsers(): Promise<User[]> {
  const response = await fetch('https://api.example.com/users');
  const users: User[] = await response.json();
  return users;
}

POST Request

TypeScriptRead-only
1
interface NewUser {
  name: string;
  email: string;
}

async function createUser(user: NewUser): Promise<User> {
  const response = await fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(user),
  });
  
  const newUser: User = await response.json();
  return newUser;
}

Error Handling

TypeScriptRead-only
1
async function fetchData<T>(url: string): Promise<T> {
  try {
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data: T = await response.json();
    return data;
  } catch (error) {
    console.error('Fetch error:', error);
    throw error;
  }
}

// Usage
const users = await fetchData<User[]>('https://api.example.com/users');

Request Configuration

TypeScriptRead-only
1
interface RequestConfig extends RequestInit {
  timeout?: number;
}

async function request<T>(url: string, config: RequestConfig = {}): Promise<T> {
  const controller = new AbortController();
  const { timeout = 5000, ...fetchConfig } = config;
  
  const timeoutId = setTimeout(() => controller.abort(), timeout);
  
  try {
    const response = await fetch(url, {
      ...fetchConfig,
      signal: controller.signal,
    });
    
    clearTimeout(timeoutId);
    
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    clearTimeout(timeoutId);
    throw error;
  }
}

HTTP Methods

MethodTypeScript Example
GETfetch(url)
POSTfetch(url, { method: 'POST', body: data })
PUTfetch(url, { method: 'PUT', body: data })
DELETEfetch(url, { method: 'DELETE' })
PATCHfetch(url, { method: 'PATCH', body: data })

Headers & Authentication

TypeScriptRead-only
1
const headers = new Headers({
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${token}`,
});

async function getAuthenticated<T>(url: string): Promise<T> {
  const response = await fetch(url, { headers });
  return response.json();
}

Best Practices

  • Always define interfaces for request/response data
  • Check response.ok before parsing JSON
  • Use generics for reusable fetch functions
  • Handle errors properly with try/catch
  • Set timeouts to avoid hanging requests
  • Use AbortController for canceling requests

Common Mistakes

  • Forgetting to await fetch and json()
  • Not handling non-200 responses
  • Using any type instead of proper interfaces
  • Missing error handling for network failures
  • Not setting Content-Type header for POST/PUT

Conclusion

TypeScript with Fetch API provides type-safe HTTP communication, reducing runtime errors and improving developer productivity. Always define interfaces for your data shapes and implement proper error handling.

Try it yourself

interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

async function getPosts(): Promise<Post[]> {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  const posts: Post[] = await response.json();
  return posts;
}

// Test it
getPosts().then(posts => console.log(posts.slice(0, 2)));

Test Your Knowledge

Q1
of 4

How to check if fetch response is successful?

A
response.success
B
response.status === 200
C
response.ok
D
response.isOk()
Q2
of 4

Which method cancels a fetch request?

A
cancel()
B
abort()
C
stop()
D
terminate()
Q3
of 4

What's the correct way to type a fetch response?

A
const data: any = await response.json()
B
const data = await response.json() as MyType
C
const data: MyType = await response.json()
D
Both B and C are correct
Q4
of 4

Which header is required for JSON POST requests?

A
Accept
B
Authorization
C
Content-Type
D
X-Requested-With

Frequently Asked Questions

How to type fetch response?

Use interfaces with async/await and type assertions.

How to handle errors?

Check response.ok and use try/catch blocks.

What is AbortController?

Cancels ongoing fetch requests.

How to set headers?

Use headers option in fetch config.

Previous

ts events

Next

ts config

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.