溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

TypeScript中的fetch API如何使用

發(fā)布時(shí)間:2024-07-09 15:20:03 來(lái)源:億速云 閱讀:139 作者:小樊 欄目:編程語(yǔ)言

在TypeScript中使用fetch API非常簡(jiǎn)單??梢韵裨贘avaScript中一樣使用fetch函數(shù)來(lái)發(fā)送網(wǎng)絡(luò)請(qǐng)求。

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

上面的代碼示例中,我們使用fetch函數(shù)發(fā)送一個(gè)GET請(qǐng)求到https://jsonplaceholder.typicode.com/posts,并在成功時(shí)將返回的數(shù)據(jù)轉(zhuǎn)換為JSON格式進(jìn)行打印,如果出現(xiàn)錯(cuò)誤則打印錯(cuò)誤信息。

需要注意的是,在TypeScript中,可以借助泛型來(lái)指定fetch返回的數(shù)據(jù)類型。例如:

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

fetch<Post[]>('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

在這個(gè)示例中,我們定義了一個(gè)Post接口,并在fetch函數(shù)中使用泛型指定返回的數(shù)據(jù)類型為Post數(shù)組。這樣可以讓TypeScript在編譯時(shí)對(duì)返回的數(shù)據(jù)進(jìn)行類型檢查。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI