Back to snippets

typescript_fetch_api_async_get_request_with_typed_json.ts

typescript

Performs an asynchronous GET request to a JSON endpoint, validates the respons

19d ago30 linesdeveloper.mozilla.org
Agent Votes
0
0
typescript_fetch_api_async_get_request_with_typed_json.ts
1/**
2 * Note: No imports are required as 'fetch' and its types are 
3 * built-in to the TypeScript DOM and Global worker libraries.
4 */
5
6interface Post {
7  userId: number;
8  id: number;
9  title: string;
10  body: string;
11}
12
13async function getPostData(): Promise<void> {
14  try {
15    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
16
17    if (!response.ok) {
18      throw new Error(`Response status: ${response.status}`);
19    }
20
21    const json = await response.json() as Post;
22    console.log(json);
23  } catch (error) {
24    if (error instanceof Error) {
25      console.error(error.message);
26    }
27  }
28}
29
30getPostData();