본문 바로가기

Fetch in TypeScript

web/javascript by 낼스 2022. 9. 4.

원본 : https://www.delftstack.com/howto/typescript/typescript-fetch/

 

Fetch in TypeScript

The fetch is a globally available native browser function that can be used to fetch resource over an HTTP connection. In TypeScript, we can use the fetch function to consume typed response data.

www.delftstack.com

// Todo type interface
interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}
function fetchToDo<T>(resourceUrl: string): Promise<T> {
  return fetch(resourceUrl).then(response => {
      // fetching the reponse body data
      return response.json<T>()
    })
}
// Consuming the fetchToDo to retrieve a Todo
fetchToDo<Todo>("https://jsonplaceholder.typicode.com/todos/2")
  .then((toDoItem) => {
    // assigning the response data `toDoItem` directly to `myNewToDo` variable which is
    // of Todo type
    let myNewToDo:Todo = toDoItem;
    // It is possible to access Todo object attributes easily
    console.log('\n id: '+ myNewToDo.id + '\n title: ' + myNewToDo.title + '\n completed: ' + myNewToDo.completed + '\n User Id: ' + myNewToDo.userId);
  });

댓글