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

解决TypeScript报错DocumentData不可赋值给never类型参数问题

报错原因

this.postComments 未显式声明类型,TypeScript 自动将其推断为 never[] 类型,该类型的数组不允许插入任何非never类型的值,因此传入DocumentData类型的commentaires时触发类型校验报错。

解决方案

步骤1:定义评论数据类型

先根据你的业务逻辑定义评论的结构,示例如下:

interface Comment {
  id: string;
  // 补充你实际业务中评论的其他字段,例如内容、发布人id、发布时间等
  content?: string;
  userId?: string;
  createTime?: Date;
  // 暂时不确定字段的话可以先用索引签名兼容
  [key: string]: any;
}

步骤2:为postComments指定类型

在你定义postComments属性的位置,显式声明类型:

// 类属性声明示例
postComments: Comment[] = [];

步骤3:调整代码中的类型断言

修改你原有函数中获取评论数据的部分,给Firestore返回的DocumentData做类型断言:

async viewPost (post: { id?: unknown }) {
  const allCommentaires = await commentsCollection.where('postId', '==', post.id).get()
  // Firestore 的 get() 方法返回的 QuerySnapshot 永远不会为 undefined,可删除冗余判断
  allCommentaires.forEach(data => {
    const commentaires = data.data() as Comment
    commentaires.id = data.id
    this.postComments.push(commentaires)
  })
  this.fullPost = post
  this.showPostModal = true
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:57:01