You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何为fetchUsers的fetch响应添加IUsers类型定义

实现方案

你可以通过以下两种常用方式给fetchUsers的响应绑定IUsers类型,注意返回值是用户对象数组,所以要用到IUsers[]数组类型:

方法1:显式声明函数返回值类型(更推荐,类型约束更清晰)

直接给fetchUsers指定返回值为Promise<IUsers[]>即可,TypeScript会自动将返回结果的类型传递给后续调用时的回调参数:

interface IUsers {
  id: number;
  name: string;
}

// 显式指定函数返回值类型
export const fetchUsers = (): Promise<IUsers[]> =>
  fetch(`/users`).then((res) => res.json());

方法2:对res.json()的结果做类型断言

如果你不想修改函数的返回值定义,也可以直接给res.json()的返回结果做类型断言:

interface IUsers {
  id: number;
  name: string;
}

export const fetchUsers = () =>
  fetch(`/users`).then((res) => res.json() as Promise<IUsers[]>);

注意:以上两种方式都是编译期的类型校验,如果需要保证运行时的类型安全,建议额外加一层返回结果的字段校验逻辑,避免后端返回结构和定义不一致导致类型定义失效。


内容的提问来源于stack exchange,提问作者Fay Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:48:02