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

TypeScript报错:类型'never'不存在'size'和'update'属性求解

问题分析与解决方案

错误原因

  1. TypeScript类型推断问题:let friendRef;未初始化,TypeScript会将其类型推断为never,导致后续访问friendRef.size和调用friendRef.update()时触发类型错误。
  2. 属性误用:size是QuerySnapshot(即代码中的friendsQuerySnapshot)的属性,用来表示查询结果的文档数量,而friendRef是DocumentReference类型,不存在size属性。

修正后的代码

既然你的查询通过limit(1)限制了最多返回1条记录,完全不需要用forEach遍历,直接从查询快照的docs数组中取第一个元素即可:

export const onRespondedToFriendRequest = functions.firestore
  .document("users/{userDocID}/notifications/{notifID}")
  .onUpdate(async (change, context) => {
    const notifID = context.params.notifID;
    const uid = context.params.userDocID; // user A
    const afterData = change.after.data();
    const friendUID = afterData?.uid; // user B (the friend)

    // 先做必要的空值判断,避免后续报错
    if (!afterData || !friendUID) return;

    // If notifID is "2" and moveOnToNextStep = true
    if (notifID === "2" && afterData.moveOnToNextStep) {
      const friendsQuerySnapshot = await fs
        .collection(`users/${friendUID}/friends`)
        .where("uid", "==", uid)
        .limit(1)
        .get();

      // 检查查询结果是否有文档
      if (!friendsQuerySnapshot.empty) {
        const friendDoc = friendsQuerySnapshot.docs[0];
        await friendDoc.ref.update({
          stat: "1",
          modifiedDate: Math.floor(Date.now() / 1000).toString(),
        });
      }
    }
  });

关键优化点

  • 用模板字符串替代字符串拼接,代码更简洁:users/${friendUID}/friends
  • 增加空值判断:afterData?.uid和!afterData || !friendUID,避免undefined导致的运行时错误
  • 直接通过friendsQuerySnapshot.empty判断是否有查询结果,替代错误的size属性访问
  • 从docs[0]直接获取唯一可能的文档,无需遍历

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:42:32