Angular+Firestore开发报错:id等属性不存在于unknown类型
Hey there! Let's work through this TypeScript error you're facing when fetching Firestore data in your NewTrainingComponent. The issue boils down to TypeScript's strict type checking—since doc.payload.doc.data() returns an unknown type by default, it doesn't let you access properties like name or duration directly. Here's how to fix it step by step:
1. Confirm Your Exercise Model
First, double-check your Exercise interface matches the structure of documents in your availableExercises collection. It should look something like this:
export interface Exercise { id?: string; // Optional if you don't store the ID in the document data name: string; duration: number; calories: number; }
2. Add Type Assertions to Firestore Data
The core fix is telling TypeScript that the data coming from Firestore matches your Exercise type. You can do this with a type assertion (as Exercise). Also, note that Firestore document IDs are stored on the doc.payload.doc.id property (not inside the document data unless you manually added it)—I noticed you were accessing doc.payload.doc.data().id before, which might be a mistake if you're using auto-generated IDs.
Here's the updated ngOnInit code, including modern RxJS pipeable operators (your current map syntax is outdated):
import { map } from 'rxjs/operators'; // Add this import at the top // ... ngOnInit(): void { this.exercises = this.db .collection<Exercise>('availableExercises') // Use generics to hint at the collection type .snapshotChanges() .pipe( map(docArray => { return docArray.map(doc => { const exerciseData = doc.payload.doc.data() as Exercise; return { id: doc.payload.doc.id, // Use the document's auto-generated ID here name: exerciseData.name, duration: exerciseData.duration, calories: exerciseData.calories }; }); }) ); }
For a more concise version, you can spread the asserted data with the ID:
return { id: doc.payload.doc.id, ...doc.payload.doc.data() as Exercise };
3. Why Square Brackets Didn't Work
When dealing with unknown type, TypeScript blocks both dot notation (data.name) and bracket notation (data['name']) until you narrow the type to something specific. The type assertion (as Exercise) tells TypeScript "trust me, this data matches the Exercise structure," which unlocks property access.
4. Optional: Verify Strict Mode
If you haven't already, check your tsconfig.json to ensure strict is set to true—this enforces strong type checking and helps catch bugs early. The error you're seeing is a side effect of this helpful feature, and our fix works perfectly with strict mode enabled.
That should resolve the "Property does not exist on type 'unknown'" errors. Let me know if you run into any other kinks!
内容的提问来源于stack exchange,提问作者Vee

