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
相关产品推荐
相关产品推荐

