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

调用Unsplash API返回响应与TypeScript推断类型不匹配如何解决?

报错原因

unsplash-js官方类型定义中,getRandom方法的返回结果默认是联合类型:

  • 当请求参数count=1时返回单个Random类型对象
  • 当count>1时返回Random[]数组
  • 请求异常/无返回时为undefined

TypeScript不会根据你传入的参数值自动缩窄result.response的类型,所以就算你传了count:10逻辑上肯定返回数组,甚至自定义了匹配返回结构的类型,TS还是会认为它的类型是Random | Random[] | undefined,和你state声明的Random[]不兼容,因此抛出类型错误。

解决方案

不用声明any,可以用以下两种方法解决:

方法1:类型断言(最简方案)

你明确知道当前请求传了count:10必定返回数组,直接给result.response加类型断言即可:

setImage(result.response as Random[]);

方法2:类型守卫(更严谨)

如果想要兼容异常情况,避免接口返回不符合预期时出现运行时错误,可以加类型判断缩窄类型:

api.photos.getRandom({ count: 10 })
  .then(result => {
    const res = result.response;
    if (res && Array.isArray(res)) {
      setImage(res);
    } else {
      setError('图片数据返回格式异常');
    }
  })
其他代码优化建议
  • useState不用手动标注返回的元组类型,React会自动推断,简化写法:
    // 代替你原来的长类型标注,效果完全一致
    const [images, setImage] = React.useState<Random[]>([]);
    const [error, setError] = React.useState('');
    
  • 你当前render部分的map回调写法有问题:用了大括号却没有return,且photo的类型应该是Random不是Photo,修正后:
    {images.map((photo: Random) => (
      <Image key={photo.id} borderRadius="md" src={photo.urls.regular} />
    ))}
    
    记得要加key属性,以及给Image组件传入实际的图片地址。

内容的提问来源于stack exchange,提问作者Esam Olwan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:54:07