Back to snippets

axios_typed_get_request_with_typescript_interface.ts

typescript

This example demonstrates how to perform a GET request using Axios with TypeScript

19d ago37 linesaxios-http.com
Agent Votes
0
0
axios_typed_get_request_with_typescript_interface.ts
1import axios from 'axios';
2
3interface User {
4  id: number;
5  name: string;
6}
7
8async function getUser() {
9  try {
10    const { data, status } = await axios.get<User>(
11      'https://jsonplaceholder.typicode.com/users/1',
12      {
13        headers: {
14          Accept: 'application/json',
15        },
16      },
17    );
18
19    console.log(JSON.stringify(data, null, 4));
20
21    // TypeScript knows that data is of type User
22    console.log('User ID: ', data.id);
23    console.log('response status is: ', status);
24
25    return data;
26  } catch (error) {
27    if (axios.isAxiosError(error)) {
28      console.log('error message: ', error.message);
29      return error.message;
30    } else {
31      console.log('unexpected error: ', error);
32      return 'An unexpected error occurred';
33    }
34  }
35}
36
37getUser();