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

Angular Firestore报错:Property 'find'不存在于类型'number'

问题原因与解决方案

错误Property 'find' does not exist on type 'number'本质是TypeScript无法正确推断出users的类型,导致它被错误识别为number类型(而非用户对象数组)。核心问题出在嵌套的combineLatest类型推断失效,加上缺少明确的接口定义辅助类型推导。

1. 定义明确的数据接口

先给Event和User定义TypeScript接口,让编译器有清晰的类型参考:

interface Event {
  id: string;
  uid: string; // 根据实际业务调整uid类型,比如number
  // 补充事件的其他字段
}

interface User {
  id: string;
  uid: string;
  // 补充用户的其他字段
}

2. 修复combineLatest的类型推断

嵌套的combineLatest返回的是单个用户对象(或undefined)的数组,但TypeScript未自动推断出正确类型,需要显式指定泛型并给collectionData标注类型:

return combineLatest<[Event[], (User | undefined)[]]>(
  of(events),
  combineLatest(
    userIds.map(userId => 
      // 给collectionData指定User类型,明确返回的用户数据结构
      collectionData<User>(query(usersRef, where('uid', '==', userId)), { idField: 'id' })
        .pipe(map(users => users[0]))
    )
  )
)

3. 给最终map函数标注明确类型

在最终的map回调中,显式标注参数类型,确保编译器识别users是用户对象数组:

map(([events, users]: [Event[], (User | undefined)[]]) => {
  return events.map((event) => {
    return {
      event,
      // 用可选链处理可能的undefined用户
      user: users.find(us => us?.uid === event.uid)
    }
  })
})

完整修改后的代码示例

import { inject } from '@angular/core';
import { Firestore, collection, collectionData, query, where } from '@angular/fire/firestore';
import { switchMap, combineLatest, of, map } from 'rxjs';
import { uniq } from 'lodash'; // 若使用其他去重工具,需对应调整

interface Event {
  id: string;
  uid: string;
  // 补充你的事件字段
}

interface User {
  id: string;
  uid: string;
  // 补充你的用户字段
}

private readonly firestore = inject(Firestore);

const eventsRef = collection<Event>(this.firestore, 'events');
const usersRef = collection<User>(this.firestore, 'users');

return collectionData(eventsRef, { idField: 'id' })
  .pipe(
    switchMap(events => {
      // 显式指定userIds类型,避免推断为unknown[]
      const userIds = uniq(events.map(ev => ev.uid)) as string[];
      return combineLatest<[Event[], (User | undefined)[]]>(
        of(events),
        combineLatest(
          userIds.map(userId => 
            collectionData<User>(query(usersRef, where('uid', '==', userId)), { idField: 'id' })
              .pipe(map(users => users[0]))
          )
        )
      )
    }),
    map(([events, users]: [Event[], (User | undefined)[]]) => {
      return events.map((event) => {
        return {
          event,
          user: users.find(us => us?.uid === event.uid)
        }
      })
    })
  )

额外说明

  • 如果你的uniq不是来自lodash,而是自定义函数,要确保它返回明确的string[]或number[]类型,避免TypeScript推断为unknown[]。
  • 使用us?.uid可选链语法,防止找不到对应用户时出现undefined读取属性的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 00:11:15