Skip to content

Commit d21d243

Browse files
docs(firestore): type reads with a converter instead of a type argument (#3838)
The README, the quickstart and the v7 upgrade guide showed collectionData<Item>(collection(firestore, 'items')), which fails with TS2345: collection() returns a reference typed DocumentData and the type argument asks for Item. docs/firestore.md cast the result with `as Observable<UserProfile[]>` instead, which compiles but checks nothing. The examples now attach a FirestoreDataConverter through withConverter, the Firebase SDK's way to type a reference, with a fromFirestore that substitutes a default for a missing or wrong field. A new "Typed reads" section in docs/firestore.md says why the two shortcuts do not give a typed read, where the default-versus-throw choice lives, and that idField performs no validation.
1 parent 419db92 commit d21d243

4 files changed

Lines changed: 69 additions & 18 deletions

File tree

‎README.md‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,19 @@ export const appConfig: ApplicationConfig = {
3535
```ts
3636
import { AsyncPipe } from '@angular/common';
3737
import { Component, inject } from '@angular/core';
38-
import { Firestore, collectionData, collection } from '@angular/fire/firestore';
38+
import { Firestore, FirestoreDataConverter, collectionData, collection } from '@angular/fire/firestore';
3939

4040
interface Item {
4141
name: string;
42+
}
43+
44+
// Types the collection and checks every document on its way in
45+
const itemConverter: FirestoreDataConverter<Item> = {
46+
toFirestore: item => item,
47+
fromFirestore: (snapshot, options) => {
48+
const data = snapshot.data(options);
49+
return { name: typeof data['name'] === 'string' ? data['name'] : '' };
50+
},
4251
};
4352

4453
@Component({
@@ -56,11 +65,13 @@ interface Item {
5665
})
5766
export class App {
5867
firestore = inject(Firestore);
59-
itemCollection = collection(this.firestore, 'items');
60-
items$ = collectionData<Item>(this.itemCollection);
68+
itemCollection = collection(this.firestore, 'items').withConverter(itemConverter);
69+
items$ = collectionData(this.itemCollection); // Observable<Item[]>
6170
}
6271
```
6372

73+
The converter is what gives the read its type. `collection()` alone returns an untyped reference. See [Typed reads](docs/firestore.md#typed-reads).
74+
6475
## Resources
6576

6677
[Quickstart](docs/install-and-setup.md) - Get your first application up and running by following our quickstart guide.

‎docs/firestore.md‎

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,27 @@ Let's explore reading data in Angular using the `collection` and `collectionData
105105
In `user-profile.component.ts`:
106106

107107
```typescript
108-
import { Firestore, collection, collectionData} from '@angular/fire/firestore';
108+
import { Firestore, FirestoreDataConverter, collection, collectionData } from '@angular/fire/firestore';
109109
import { Component, inject } from '@angular/core';
110110
import { Observable } from 'rxjs';
111111

112+
export interface UserProfile {
113+
username: string;
114+
}
115+
116+
/* A converter translates between stored documents and your own type.
117+
* fromFirestore runs on every document read, so it is where a missing
118+
* or wrong field gets its default. */
119+
export const userProfileConverter: FirestoreDataConverter<UserProfile> = {
120+
toFirestore: profile => profile,
121+
fromFirestore: (snapshot, options) => {
122+
const data = snapshot.data(options);
123+
return {
124+
username: typeof data['username'] === 'string' ? data['username'] : '',
125+
};
126+
},
127+
};
128+
112129
@Component ({
113130
selector: 'app-user-profile',
114131
standalone: true,
@@ -119,17 +136,15 @@ export class UserProfileComponent {
119136
users$: Observable<UserProfile[]>;
120137

121138
constructor() {
122-
// get a reference to the user-profile collection
123-
const userProfileCollection = collection(this.firestore, 'users');
139+
// get a reference to the users collection, typed through the converter
140+
const userProfileCollection = collection(this.firestore, 'users').withConverter(userProfileConverter);
124141

125142
// get documents (data) from the collection using collectionData
126-
this.users$ = collectionData(userProfileCollection) as Observable<UserProfile[]>;
143+
this.users$ = collectionData(userProfileCollection); // Observable<UserProfile[]>
127144
}
128145
}
129-
export interface UserProfile {
130-
username: string;
131-
}
132146
```
147+
133148
`collectionData` returns an `observable` that can we can use to display the data in the template. In `user-profile.component.html`:
134149

135150
```html
@@ -145,6 +160,17 @@ export interface UserProfile {
145160

146161
The `async` pipe handles unsubscribing from observables.
147162

163+
#### Typed reads
164+
165+
`collection()` and `doc()` return references typed as `DocumentData`, and `collectionData()` and `docData()` return whatever type the reference carries (`docData()` adds `undefined` for a document that does not exist). Two tempting shortcuts do not give you a typed read:
166+
167+
* `collectionData<UserProfile>(collection(this.firestore, 'users'))` does not compile (`TS2345`), because the reference says `DocumentData` and the type argument says `UserProfile`.
168+
* `collectionData(...) as Observable<UserProfile[]>` compiles, but it only tells the compiler what you hope is stored. Nothing checks the documents.
169+
170+
`withConverter()` is the Firebase SDK's way to type a reference. Attach a `FirestoreDataConverter<T>` and every read through that reference returns `T`, with no type argument and no cast. Because `fromFirestore` runs on every document, it is also where you decide what happens to a document that does not match your type. The example above substitutes a default, so one malformed document does not stop the list from rendering. Throwing inside `fromFirestore` instead would error the `collectionData` observable at the first bad document, and the subscription would end.
171+
172+
The `idField` option, `collectionData(ref, { idField: 'id' })`, copies each document's id onto the returned object. It does not validate any other field. With a converter you can do the same inside `fromFirestore` with `snapshot.id`.
173+
148174
### Writing data
149175

150176
To write to Cloud Firestore use the `addDoc` function. It will create a new document at the path specified by the collection. In `user-profile.component.ts`, we'll update the code to add a new document on a `<button>` click.

‎docs/install-and-setup.md‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,21 @@ In `/src/app/app.ts`:
7878
import { Component, inject } from '@angular/core';
7979
import { AsyncPipe } from '@angular/common';
8080
import { Observable } from 'rxjs';
81-
import { Firestore, collection, collectionData } from '@angular/fire/firestore';
81+
import { Firestore, FirestoreDataConverter, collection, collectionData } from '@angular/fire/firestore';
8282

8383
interface Item {
8484
name: string;
8585
}
8686

87+
// Types the collection and checks every document on its way in
88+
const itemConverter: FirestoreDataConverter<Item> = {
89+
toFirestore: item => item,
90+
fromFirestore: (snapshot, options) => {
91+
const data = snapshot.data(options);
92+
return { name: typeof data['name'] === 'string' ? data['name'] : '' };
93+
},
94+
};
95+
8796
@Component({
8897
selector: 'app-root',
8998
imports: [AsyncPipe],
@@ -95,12 +104,14 @@ export class App {
95104
items$: Observable<Item[]>;
96105

97106
constructor() {
98-
const aCollection = collection(this.firestore, 'items')
99-
this.items$ = collectionData<Item>(aCollection);
107+
const aCollection = collection(this.firestore, 'items').withConverter(itemConverter);
108+
this.items$ = collectionData(aCollection);
100109
}
101110
}
102111
```
103112

113+
The converter is what gives the read its type. `collection()` alone returns an untyped reference. The [Firestore guide](firestore.md#typed-reads) explains the pattern.
114+
104115
Open `/src/app/app.html`:
105116

106117
```html

‎docs/version-7-upgrade.md‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ So developing with the new AngularFire is easy, you can use it just like the van
129129

130130
#### Alternatives to v6 APIs
131131

132+
In the modular column, `docRef` is a `DocumentReference<T>` typed through `withConverter(converter)`, where `converter` is a `FirestoreDataConverter<T>`. A reference from a plain `doc()` or `collection()` call is typed `DocumentData`, and the `<T>` calls below do not compile on one. See [Typed reads](firestore.md#typed-reads).
133+
132134
<table>
133135
<thead>
134136
<tr>
@@ -207,7 +209,7 @@ deleteDoc(docRef) // Promise<void>
207209

208210
```ts
209211
import { collection } from '@angular/fire/firestore';
210-
collection<T>(docRef, 'bar') // CollectionReference<T>
212+
collection(docRef, 'bar').withConverter(converter) // CollectionReference<T>
211213
```
212214
</td>
213215
</tr>
@@ -229,7 +231,7 @@ docSnapshots<T>(docRef) // Observable<DocumentSnapshot<T>>
229231

230232
```ts
231233
import { docData } from '@angular/fire/firestore';
232-
docData<T>(docRef) // Observable<T>
234+
docData<T>(docRef) // Observable<T | undefined>
233235
```
234236
</td>
235237
</tr>
@@ -259,14 +261,15 @@ import {
259261
collection,
260262
getFirestore
261263
} from '@angular/fire/firestore';
262-
import { first } from 'rxjs/operators';
263-
import { IFoo } from '../interfaces';
264+
import { concatMap, first } from 'rxjs/operators';
265+
// a FirestoreDataConverter<IFoo>, see firestore.md "Typed reads"
266+
import { fooConverter } from '../foo-converter';
264267

265268
export { getFirestore };
266269

267270
export const fooData = firestoreInstance$.pipe(
268271
first(),
269-
concatMap(firestore => collectionData<IFoo>(collection(firestore, 'foo'))),
272+
concatMap(firestore => collectionData(collection(firestore, 'foo').withConverter(fooConverter))),
270273
);
271274
```
272275

0 commit comments

Comments
 (0)