温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

TypeScript中的fetch API如何使用

发布时间:2024-07-09 15:20:03 来源:亿速云 阅读:138 作者:小樊 栏目:编程语言

在TypeScript中使用fetch API非常简单。可以像在JavaScript中一样使用fetch函数来发送网络请求。

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

上面的代码示例中,我们使用fetch函数发送一个GET请求到https://jsonplaceholder.typicode.com/posts,并在成功时将返回的数据转换为JSON格式进行打印,如果出现错误则打印错误信息。

需要注意的是,在TypeScript中,可以借助泛型来指定fetch返回的数据类型。例如:

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));

在这个示例中,我们定义了一个Post接口,并在fetch函数中使用泛型指定返回的数据类型为Post数组。这样可以让TypeScript在编译时对返回的数据进行类型检查。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI