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

TypeScript访问对象属性报ts(2339):属性不存在于string类型

问题根源
  • 错误出在数组遍历方式:你使用了for...in语法遍历数组,该语法遍历得到的是对象/数组的字符串类型键名,而非数组元素本身。
  • 对数组来说,for...in拿到的i是"0"、"1"这类字符串格式的索引值,TypeScript会判定i的类型为string,自然不存在docPath、update属性,因此抛出两个ts(2339)类型错误。
  • 额外注意:for...in还会遍历到原型链上挂载的可枚举属性,本身就不适合用来遍历数组提取元素。
修正方法

选择任意一种符合数组遍历逻辑的写法替换原有for...in循环即可:

方案1:使用for...of直接遍历数组元素(改动最小,最贴合原有逻辑)

修正后完整代码:

export const useBatchUpdateDocTask = () => {
  return useTask(function* (
    signal,
    updatesArray: {
      docPath: string;
      update: {
        [x: string]: any;
      };
    }[]
  ) {
    const batch = writeBatch(db);
    // 替换for...in为for...of,直接拿到数组每一项元素
    for (const item of updatesArray) {
      const docRef = doc(db, item.docPath);
      batch.update(docRef, item.update);
    }
    yield batch.commit();
  });
};

方案2:使用Array.forEach遍历

const batch = writeBatch(db);
updatesArray.forEach((item) => {
  const docRef = doc(db, item.docPath);
  batch.update(docRef, item.update);
});
yield batch.commit();

方案3:使用传统索引for循环,通过索引取元素

如果习惯用索引遍历,注意不要直接在索引值上访问属性,要先通过索引取到数组对应项:

const batch = writeBatch(db);
for (let index = 0; index < updatesArray.length; index++) {
  const item = updatesArray[index];
  const docRef = doc(db, item.docPath);
  batch.update(docRef, item.update);
}
yield batch.commit();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 06:24:25