调用API时如何将类型分配给API响应
我在项目中使用打字稿,当我使用获取来调用API时,响应的类型是任何。
const response = await fetch(url);
我知道此响应的数据结构是一个对象,
{id: string; code: string}
我可以使用以下方式将类型分配给响应?如果没有,我可以了解此要求的最佳实践吗?
const response: {id: string; code: string} = await fetch(url);
如果我只需要ID,可以这样做吗?
const { id }: {id: string} = await fetch(url);
I am using TypeScript in my project and when I use fetch to call the API, the type of response is any.
const response = await fetch(url);
I know the data structure of this response is an object
{id: string; code: string}
Can I use below way to assign the type to response? If not, may I please know the best practise for this requirement?
const response: {id: string; code: string} = await fetch(url);
If I only need id, is it ok to do so?
const { id }: {id: string} = await fetch(url);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该创建键入获取并在需要打字响应的地方使用它:
You should create typed fetch and use it where you need typed response: