您好,登錄后才能下訂單哦!
在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)行類型檢查。
免責(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)容。