【问题标题】:REACT Typescript fetch/ axios error - following properties from type 'Address[]': length, pop, push, concat, and 28 more. TS2740REACT Typescript fetch/axios 错误 - 来自类型“地址 []”的以下属性:长度、弹出、推送、连接和 28 个更多。 TS2740
【发布时间】:2025-12-28 04:15:07
【问题描述】:
import {Address} from './address.model';
export const get = async ():Promise<Address[]>    =>  {  
  
  return await fetch(`${apiUrl}`)
  .then(response => {
    if (!response.ok) {
      throw new Error(response.statusText)
    }
    return   response.json() as Promise<Address[]>;
  })

//--------------caling from
 React.useEffect(() => {
    let newArr: Address[] = get()  ;
     setEntities(newArr);
  } , [])

//-------------抛出以下错误: 类型“Promise

”缺少类型“Address[]”的以下属性:length、pop、push、concat 和另外 28 个。 TS2740

【问题讨论】:

    标签: reactjs typescript axios fetch


    【解决方案1】:

    忽略有问题的转换 (cf.as Promise&lt;Address[]&gt;),您需要等待您的 get() 函数来获取 Address[] 类型,所以

     React.useEffect(() => {
        async get() => {
         // do the IO
        }
        const newArr: Address[] = await get()
        setEntities(newArr)
      } , [])
    

    【讨论】:

    • 好点。但是添加异步会引发以下错误:'() => Promise' 类型的参数不可分配给'EffectCallback' 类型的参数。类型 'Promise' 不可分配给类型 'void | (() => void | 未定义)'。类型 'Promise' 不可分配给类型 '() => void |不明确的'。类型 'Promise' 不匹配签名 '(): void |不明确的'。 TS2345
    • 异步内部 useEffect 需要这样:*.com/questions/56838392/…。我会继续更改答案。
    • 啊,是的,我总是犯这个错误。我将更新我的代码块以匹配下一个人。
    最近更新 更多