AngularFire中使用arrayUnion更新Firestore数组字段报错求助
解决AngularFire中使用arrayUnion更新Firestore数组字段的类型错误
方法1:类型断言快速解决
直接给arrayUnion的返回值添加类型断言,让TypeScript认可它符合CarAttachment[]的类型要求:
addCarAttachment(carId: string, attachment: CarAttachment) { return this.firestore.collection<Car>('car').doc(carId).update({ attachments: FieldValue.arrayUnion(attachment) as unknown as CarAttachment[], }); }
方法2:定义兼容的更新类型(更严谨)
创建一个包含FieldValue兼容类型的更新接口,避免类型断言的粗暴处理:
// 定义支持FieldValue的Car更新类型 type CarUpdate = Omit<Car, 'attachments'> & { attachments?: CarAttachment[] | FieldValue; }; addCarAttachment(carId: string, attachment: CarAttachment) { return this.firestore.collection<Car>('car').doc(carId).update({ attachments: FieldValue.arrayUnion(attachment), } as Partial<CarUpdate>); }
错误原因说明
TypeScript根据Car接口推断update方法的参数必须是Partial<Car>类型,其中attachments字段被限定为CarAttachment[]。但FieldValue.arrayUnion()返回的是Firestore用于处理数组操作的特殊FieldValue类型,二者类型不匹配引发报错。实际上Firestore会在执行更新时自动解析FieldValue指令,所以只需让TypeScript接受该类型即可。
内容的提问来源于stack exchange,提问作者byteram
相关产品推荐
相关产品推荐

